简体   繁体   English

从总和为所需总数的值列表中确定所有可能的组合

[英]Determining all possible combinations from a list of values that sum to desired total

I was asked a programming question by a friend about how to determine all possible combinations of values from a set can be added to make a desired total. 我被问到一个朋友关于如何确定一组中所有可能的值组合的编程问题可以被添加以产生所需的总数。 I have a solution, but it is less than elegant (its basically just a series of for-loops and if-statements). 我有一个解决方案,但它不是优雅的(它基本上只是一系列for循环和if语句)。 I'm sure dplyr has a solution that I can't think of, as I know how useful it is but I just haven't gotten very good at it yet. 我确信dplyr有一个我无法想到的解决方案,因为我知道它有多么有用,但我还没有得到很好的解决方案。 I will post the question and my script below. 我将在下面发布问题和我的脚本。

Question: There is a target with six rings on it, each ring is worth a different value. 问题:目标上有六个环,每个环值相同。 These values are either 1, 2, 3, 4, 5, or 6. How many different combinations of rings can you use to score EXACTLY 9 points? 这些值可以是1,2,3,4,5或6.您可以使用多少种不同的戒指组合来获得9分?

So to consider: Order is not important You can use as few or as many values as you want You can get the same value more than once (so 9 1's is a totally valid option) 所以要考虑:顺序并不重要您可以根据需要使用尽可能少的值您可以多次获得相同的值(因此9 1是完全有效的选项)

I had considered first using combn() from combinat package, but combn() does not replace values. 我曾经考虑过首先使用combinat包中的combn(),但是combn()不会替换值。

Then I decided to use a series of nested for loops and if statements (I truncated it to where you could only use a max of 6-values, because while I may have free time, I'm not a masochist about to write a loop that allows up to 9-values). 然后我决定使用一系列嵌套的for循环和if语句(我把它截断到你只能使用最多6个值的地方,因为虽然我可能有空闲时间,但我不是一个关于写循环的受虐狂允许最多9个值)。 So essentially, it is running through 6 for-loops worth of possible values. 从本质上讲,它正在运行6个for循环,值得一些可能的值。 I included the number 0 to the list of possible values to represent no attempt when I only need 2 values instead of 6 (so 4+5+0+0+0+0 is a valid output in this loop, but it wouldn't be able to do 4+5 as it would always try to add more non-zero values). 我将数字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

I created an empty data.frame to store solutions, and then within the loop, I created a test to see if a new solution in the loop matches a combination of values previously found, and if so, it would not rbind() that to the data.frame. 我创建了一个空的data.frame来存储解决方案,然后在循环中,我创建了一个测试,以查看循环中的新解决方案是否匹配先前找到的值的组合,如果是,则不会rbind() data.frame。

I'm sure there is a better way to do this, one that allows a dynamic max number of values (so it could be soft coded in this case to change the max number of values in each solution to 9 instead of my hard-coded 6, or drop it to 5 if my desired total was 5 instead of 9). 我确信有一种更好的方法可以实现这一点,允许动态最大数量的值(因此在这种情况下可以通过软编码将每个解决方案中的最大值更改为9而不是我的硬编码6,如果我想要的总数是5而不是9,则将其降至5)。 If you have any suggestions to make this less of a clunky, loop-filled mess, it would be appreciated! 如果你有任何建议,使这不那么笨重,循环填补一团糟,我们将不胜感激!

You can maybe try this : 你可以试试这个:

    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

This is the function : 这是功能:

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

Following should list all the combinations 以下应列出所有组合

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM