My code is currently taking 4 dice rolls and changing the values to 8 if they can be summed to 8.
My function is able to correctly change (1,3,4,5) to (5,8) as required. However I run into a problem if my Dice roll is ( 1,2,6,5) for example as It is possible for two combinations of 8 to be made. eg (6,2 could be used or 1,2,5). I need my code to only output One of these solutions and I can't grasp how to do this.
target2 <- function(x)
{
roll <- (x)
library(dplyr)
comboes <- Reduce( f=append, lapply( 2:4, function(m)combn(x=roll, m=m) %>% as.data.frame %>%
as.list ) )
i.is.eight <- which( sapply( comboes, sum ) == 8 )
check <- c(i.is.eight)
if((length(check) == 0))
return(roll)
else if( length(check) >= 1 ){
lapply( i.is.eight,function(i) {
roll.i <- comboes[[i]]
## base is the dice that did not take part in the sum
base <- roll
for( r in roll.i ) {
base <- base[ -match( r, base ) ]
}
answer <- c( base, 8 )
return(answer)
}) %>% unique
}
}
( x <-sample(1:6, 4, replace=TRUE))
target2(x)
I get my code isn't the clearest so happy to explain. Any Help would be greatly appreciated.
You could just store all answers in a list and just return the first element of that list.
target2 <- function(x)
{
roll <- (x)
library(dplyr)
comboes <- Reduce( f=append, lapply( 2:4, function(m)combn(x=roll, m=m) %>% as.data.frame %>%
as.list ) )
i.is.eight <- which( sapply( comboes, sum ) == 8 )
check <- c(i.is.eight)
if((length(check) == 0))
return(roll)
else if( length(check) >= 1 ){
answers <-lapply( i.is.eight,function(i) {
roll.i <- comboes[[i]]
## base is the dice that did not take part in the sum
base <- roll
for( r in roll.i ) {
base <- base[ -match( r, base ) ]
}
answer <- c( base, 8 )
return(answer)
})
return(answers[[1]])
}
}
( x <-sample(1:6, 4, replace=TRUE))
target2(x)