【问题标题】:Getting all the combination of numbers from a list that would sum to a specific number从列表中获取所有数字组合,总和为特定数字
【发布时间】:2018-05-27 00:18:00
【问题描述】:

我有以下数字 list (1,3,4,5,7,9,10,12,15),我想从这个 list 中找出所有可能的 3 数字组合,总和为 20

我对@9​​87654327@ 的研究使我找到了这篇文章: Finding all possible combinations of numbers to reach a given sum

Mark 提供的解决方案如下:

subset_sum = function(numbers,target,partial=0){
if(any(is.na(partial))) return()
s = sum(partial)
if(s == target)  print(sprintf("sum(%s)=%s",paste(partial[-1],collapse="+"),target))
if(s > target) return()
for( i in seq_along(numbers)){
n = numbers[i]
remaining = numbers[(i+1):length(numbers)]
subset_sum(remaining,target,c(partial,n))
}
}

但是,我很难尝试调整这组代码以匹配我的问题。或者可能有更简单的解决方案?

我希望R 中的输出显示数字列表。

任何帮助将不胜感激。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以使用combn 函数和过滤器来满足您的条件。我已经分两步执行了以下计算,但也可以单步执行。

    v <-  c(1,3,4,5,7,9,10,12,15)
    AllComb <- combn(v, 3)   #generates all combination taking 3 at a time.
    PossibleComb  <- AllComb[,colSums(AllComb) == 20]  #filter those with sum == 20
    
    #Result: 6 sets of 3 numbers (column-wise) 
    PossibleComb
    #      [,1] [,2] [,3] [,4] [,5] [,6]
    # [1,]    1    1    1    3    3    4
    # [2,]    4    7    9    5    7    7
    # [3,]   15   12   10   12   10    9
    # 
    
    # Result in list
    split(PossibleComb, col(PossibleComb))
    
    # $`1`
    # [1]  1  4 15
    # 
    # $`2`
    # [1]  1  7 12
    # 
    # $`3`
    # [1]  1  9 10
    # 
    # $`4`
    # [1]  3  5 12
    # 
    # $`5`
    # [1]  3  7 10
    # 
    # $`6`
    # [1] 4 7 9
    

    【讨论】:

      【解决方案2】:

      combn 也有一个FUN 参数,我们可以将其描述为输出为list,然后根据条件输出Filter list 元素

      Filter(function(x) sum(x) == 20, combn(v, 3, FUN = list))
      #[[1]]
      #[1]  1  4 15
      
      #[[2]]
      #[1]  1  7 12
      
      #[[3]]
      #[1]  1  9 10
      
      #[[4]]
      #[1]  3  5 12
      
      #[[5]]
      #[1]  3  7 10
      
      #[[6]]
      #[1] 4 7 9
      

      数据

      v <-  c(1,3,4,5,7,9,10,12,15)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-03
        • 1970-01-01
        相关资源
        最近更新 更多