-1

鉴于我有向量和目标编号

target.mountain <- 10

Roll_dice <- sample(1:6, 4, replace=TRUE)

Roll_dice生产 [1] 6, 5, 3, 2为例

如何通过将列表中的 2、3 或 4 个值组合在一起来生成所有数字的列表以及将Roll_dice它们加在一起的所有方法Roll_dice

例如[1] 2, 3, 5, 5, 6, 7, 11, ....

4

2 回答 2

2

我希望您查看RccpAlgos-package,它有一些很棒(而且速度很快!)的功能,用于对具有约束的组合/排列进行快速操作。

更新

library(RcppAlgos)
library(vecsets)
library(data.table)

target.mountain <- 10
Roll_dice       <- c(5, 5, 3, 2)

L <- lapply( 2:4, function(x) {
  as.data.table(comboGeneral( Roll_dice, 
                x, 
                constraintFun = "sum", 
                comparisonFun = "==", 
                limitConstraints = target.mountain ),
                keep.rownames = TRUE )
})
# [[1]]
# V1 V2
# 1:  5  5
# 
# [[2]]
# V1 V2 V3
# 1:  2  3  5

#so 5-5 of 2-3-5 can be chosen to get to 10

#remaining dice
DT <- data.table::rbindlist( L, fill = TRUE )

remains <- lapply( transpose(DT), function(x) {
  v <- as.vector(x)
  v <- v[ !is.na(v) ]
  sum( vecsets::vsetdiff( Roll_dice, v) )
})

remains
#witrh leftovers:
# $V1
# [1] 5
# 
# $V2
# [1] 5

旧答案

library(RcppAlgos)
target.mountain <- 10
Roll_dice <- c(6, 4, 5, 5)
sapply( 2:4, function(x) {
  comboGeneral( Roll_dice, 
                x, 
                constraintFun = "sum", 
                comparisonFun = "==", 
                limitConstraints = target.mountain )
})

# [[1]]
#      [,1] [,2]
# [1,]    4    6
# [2,]    5    5
# 
# [[2]]
# [,1] [,2] [,3]
# 
# [[3]]
# [,1] [,2] [,3] [,4]
于 2021-03-30T13:42:57.690 回答
0

像这样的东西?

> sapply(
+   2:4,
+   function(k) combn(Roll_dice, k, sum)
+ )
[[1]]
[1] 11  9  8  8  7  5

[[2]]
[1] 14 13 11 10

[[3]]
[1] 16

或者你需要这个吗?

> lapply(
+   setNames(2:4, 2:4),
+   function(k) target.mountain %in% combn(Roll_dice, k, sum)
+ )
$`2`
[1] FALSE

$`3`
[1] TRUE

$`4`
[1] FALSE
于 2021-03-30T13:14:48.980 回答