【发布时间】:2021-03-31 22:11:25
【问题描述】:
我的代码目前正在掷 4 次骰子,如果它们的总和为 8,则将值更改为 8。
我的函数能够根据需要正确地将 (1,3,4,5) 更改为 (5,8)。但是,如果我的骰子掷骰是(1,2,6,5),例如,我会遇到一个问题,因为可以进行 8 的两种组合。例如(可以使用 6,2 或 1,2,5)。我需要我的代码只输出这些解决方案之一,但我不知道如何做到这一点。
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)
我知道我的代码不是最清楚的,所以很乐意解释。任何帮助将不胜感激。
【问题讨论】:
-
您可以使用
set.seed(n)设置一个案例来说明您的查询吗? -
看,有一个类似的任务。也许会有所帮助stackoverflow.com/questions/66857586/…
-
即使是您的工作示例
(1,3,4,5) -> (5,8),(1,4,8)也不能成为解决方案吗?因此,您的代码在某些情况下可以使用多种解决方案...