[英]Determining all possible combinations from a list of values that sum to desired total
我被问到一个朋友关于如何确定一组中所有可能的值组合的编程问题可以被添加以产生所需的总数。 我有一个解决方案,但它不是优雅的(它基本上只是一系列for循环和if语句)。 我确信dplyr有一个我无法想到的解决方案,因为我知道它有多么有用,但我还没有得到很好的解决方案。 我将在下面发布问题和我的脚本。
问题:目标上有六个环,每个环值相同。 这些值可以是1,2,3,4,5或6.您可以使用多少种不同的戒指组合来获得9分?
所以要考虑:顺序并不重要您可以根据需要使用尽可能少的值您可以多次获得相同的值(因此9 1是完全有效的选项)
我曾经考虑过首先使用combinat包中的combn(),但是combn()不会替换值。
然后我决定使用一系列嵌套的for循环和if语句(我把它截断到你只能使用最多6个值的地方,因为虽然我可能有空闲时间,但我不是一个关于写循环的受虐狂允许最多9个值)。 从本质上讲,它正在运行6个for循环,值得一些可能的值。 我将数字0包含在可能的值列表中以表示没有尝试,当我只需要2个值而不是6时(所以4 + 5 + 0 + 0 + 0 + 0在此循环中是有效输出,但它不会能够做4 + 5,因为它总是试图添加更多的非零值)。
## Create a vector x with possible values
x = c(1,2,3,4,5,6)
## Add in value 0 because I need to be able to write this dumb loop that allows many terms to be used, but also allows smaller amounts of terms to be used
x = c(x,0);x
## Creating empty data.frame to input solutions to so that I can check for uniqueness of solution
df = data.frame("a" = as.numeric(),
"b" = as.numeric(),
"c" = as.numeric(),
"d" = as.numeric(),
"e" = as.numeric(),
"f" = as.numeric())
for (a in x){
for (b in x){
for (c in x){
for (d in x){
for (e in x){
for (f in x){
m = sum(a,b,c,d,e,f)
if(m == 9) {
p = 0
n = c(a,b,c,d,e,f)
if (nrow(df) == 0){
df[1,] = n
}
if (nrow(df) >= 1){
for (i in (1:nrow(df))){
if(setequal(n,df[i,]) == TRUE){
p = p+1
}}
if(p == 0){
df = rbind(df,n)
}
}
}
}
}
}
}
}
}
## Convert any 0 values to NA
df[df==0] = NA
## Check Solutions
df
我创建了一个空的data.frame来存储解决方案,然后在循环中,我创建了一个测试,以查看循环中的新解决方案是否匹配先前找到的值的组合,如果是,则不会rbind() data.frame。
我确信有一种更好的方法可以实现这一点,允许动态最大数量的值(因此在这种情况下可以通过软编码将每个解决方案中的最大值更改为9而不是我的硬编码6,如果我想要的总数是5而不是9,则将其降至5)。 如果你有任何建议,使这不那么笨重,循环填补一团糟,我们将不胜感激!
你可以试试这个:
library(modelr)
library(dplyr)
range = 1:6
df = data.frame("a" = range,
"b" = range,
"c" = range,
"d" = range,
"e" = range,
"f" = range)
data_grid(df,a,b,c,d,e,f) %>%
mutate(sum = a+b+c+d+e+f) %>%
filter(sum == 9) %>% nrow
这是功能:
foo <- function(sum_needed, max_value){
range <- 1:max_value
df = data.frame("a" = range,
"b" = range,
"c" = range,
"d" = range,
"e" = range,
"f" = range)
result <- data_grid(df,a,b,c,d,e,f) %>%
mutate(sum = a+b+c+d+e+f) %>%
filter(sum == sum_needed) %>% nrow
return(result)
}
foo(9,6)
#[1] 56
x = 1:6
mysum = 9
#Repeat each element of x as long the sum of repetitions does not exceed mysum
temp = rep(x, floor(mysum/x))
#Calculate total unique combinations of temp that sum up to mysum
sum(sapply(1:max(floor(mysum/x)),
function(i) sum(rowSums(unique(t(combn(temp, i)))) == mysum)))
#[1] 26
以下应列出所有组合
sapply(1:max(floor(mysum/x)), function(i){
temp2 = unique(t(combn(temp, i)))
temp2[rowSums(temp2) == mysum,]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.