问题描述
给定向量和目标数
target.mountain <- 10
Roll_dice <- sample(1:6,4,replace=TRUE)
使用 Roll_dice
生产
[1] 6,5,3,2
为例
如何通过将 Roll_dice
中的 2、3 或 4 个值组合到一个列表中来生成 Roll_dice
中所有数字的列表以及将它们加在一起的所有方法
例如[1] 2,6,7,11,....
解决方法
我希望您查看 RccpAlgos
-包,它有一些很棒(而且速度很快!)的函数,用于对带约束的组合/排列进行快速操作。
更新
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)
sapply( 2:4,function(x) {
comboGeneral( Roll_dice,limitConstraints = target.mountain )
})
# [[1]]
# [,1] [,2]
# [1,] 4 6
# [2,] 5 5
#
# [[2]]
# [,2] [,3]
#
# [[3]]
# [,3] [,4]
,
类似的东西?
> 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,sum)
+ )
$`2`
[1] FALSE
$`3`
[1] TRUE
$`4`
[1] FALSE