算法:对于所有组合求和一个数字列表

23

我有一个数字列表,想要将所有不同的组合相加。

例如:

  • 数字为1、4、7和13
  • 输出应该是:


1+4=5
1+7=8
1+13=14
4+7=11
4+13=17
7+13=20
1+4+7=12
1+4+13=18
1+7+13=21
4+7+13=24
1+4+7+13=25

有没有一种公式可以用不同的数字来计算这个问题?


1
这与欧拉计划有关吗? - Kenan Banks
你要写一个Kakuro求解器(或创建器)吗? - David Koelle
15个回答

0
public static void main(String[] args) {
        // this is an example number
        long number = 245L;
        int sum = 0;

        if (number > 0) {
            do {
                int last = (int) (number % 10);
                sum = (sum + last) % 9;
            } while ((number /= 10) > 0);
            System.err.println("s = " + (sum==0 ? 9:sum);
        } else {
            System.err.println("0");
        }
    }

0

set 是和的集合,list 是原始数字的列表。

这是 Java 代码。

public void subSums() {
    Set<Long> resultSet = new HashSet<Long>();
    for(long l: list) {
        for(long s: set) {
            resultSet.add(s);
            resultSet.add(l + s);
        }
        resultSet.add(l);
        set.addAll(resultSet);
        resultSet.clear();
    }
}

0
如果您想避免维护成本,那么您可能会对查看GNU科学库感兴趣。实际上,对于较长的序列求和过程将变得非常昂贵(比逐步生成单个排列更为昂贵),大多数架构都具有SIMD/向量指令,可以提供相当惊人的加速效果(我可以提供这些实现的示例,但我还不能发布URL)。

0

这不是用来生成总和的代码,而是生成排列的代码。在您的情况下:

1; 1,4; 1,7; 4,7; 1,4,7; ...

如果我周末有空,并且觉得有趣,我可以修改它以生成总和。

这只是来自Igor Ostrovsky博客标题为“使用LINQ简化程序的7个技巧”(http://igoro.com/archive/7-tricks-to-simplify-your-programs-with-linq/)的有趣的LINQ代码片段。

T[] arr = …;
var subsets = from m in Enumerable.Range(0, 1 << arr.Length)
              select
                  from i in Enumerable.Range(0, arr.Length)
                  where (m & (1 << i)) != 0
                  select arr[i];

0

谢谢 Zach,

我正在创建一个银行对账解决方案。我把你的代码放入 jsbin.com 进行了一些快速测试,并用 Javascript 生成了这个:

function f(numbers,ids, index,  sum, output, outputid, find )
{
    if (index == numbers.length){
          var x ="";
          if (find == sum) {
              y= output + " } = " + sum + "  " + outputid + " }<br/>" ;
          }
        return;
    }
    f(numbers,ids, index + 1, sum + numbers[index], output + " " + numbers[index], outputid + " " + ids[index], find);
    f(numbers,ids, index + 1, sum, output, outputid,find);
}

var y;

f( [1.2,4,7,13,45,325,23,245,78,432,1,2,6],[1,2,3,4,5,6,7,8,9,10,11,12,13], 0, 0, '{','{', 24.2);
if (document.getElementById('hello')) {
  document.getElementById('hello').innerHTML = y;
}

我需要它生成一个ID列表,以便从下一个匹配的数字中排除。

我将使用vb.net发布我的最终解决方案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接