【问题标题】:match elements to a list of sums将元素与总和列表匹配
【发布时间】:2014-02-21 03:40:41
【问题描述】:

如果我有一个数字数组和一个总计数组元素的总和列表,那么确定总和中包含哪些元素的最有效方法(或至少不是暴力破解)是什么?

一个简化的示例可能如下所示:

数组 = [6, 5, 7, 8, 6, 12, 16] 总和 = [14, 24, 22]

我想知道:

14 包括 8、6

24 包括 5、7、12

22 包括 6、16

function matchElements(arr, sums) {
    var testArr;
    function getSumHash() {
        var hash = {},
            i;
        for (i = 0; i < sums.length; i++) {
            hash[sums[i]] = [];
        }
        return hash;
    }
    sums = getSumHash();
    // I don't have a good sense of where to start on what goes here...
    return sumHash;
}

var totals = matchElements([6, 5, 7, 8, 6, 12, 16], [14,24,22]),
    total;

for (total in totals) {
   console.log(total + "includes", totals[total])
}

http://jsfiddle.net/tTMvP/

我知道总会有至少一个正确答案,我只需要检查数字,我不需要配对有重复的索引,只需配对与总数相关的值.是否有解决此类问题的既定功能?

这只是一个 javascript 问题,因为这是我编写解决方案所用的语言,这更像是一个通过 Javascript 过滤的一般数学相关问题。如果这不是适当的论坛,我欢迎重定向到适当的堆栈交换站点。

【问题讨论】:

  • 虽然我可以使用你所说的“蛮力”,但我不知道有什么“快速”算法来实现它。
  • 是的,我就是这么想的。我之所以这么说是因为我记得 xkcd 动画片中的一些刺拳,他告诉服务员在使用类似的问题时不要使用蛮力计算他的小费(我认为),这不是最好的理由哈哈......任何可以消除的东西都匹配元素会是首选,但我会满足于蛮力,我只是希望避免它。
  • roryhart.net/code/xkcd-np-complete-restaurant-order 这是解决问题的人,不幸的是我对Minizinc一无所知,显然它是用于“约束编程”中的建模问题。所以这很有趣,但没有帮助。

标签: javascript algorithm discrete-mathematics constraint-programming subset-sum


【解决方案1】:

好吧,诅咒我,这是我的敲门声,欢迎改进:)

我相信这是Bin Packing Problemknapsack problem

Javascript

通用Power Set函数

function powerSet(array) {
    var lastElement,
        sets;

    if (!array.length) {
        sets = [[]];
    } else {
        lastElement = array.pop();
        sets = powerSet(array).reduce(function (previous, element) {
            previous.push(element);
            element = element.slice();
            element.push(lastElement);
            previous.push(element);

            return previous;
        }, []);
    }

    return sets;
}

减少幂集中的副本,即我们不希望 [6, 8] 和 [8, 6] 它们是相同的

function reducer1(set) {
    set.sort(function (a, b) {
        return a - b;
    });

    return this[set] ? false : (this[set] = true);
}

主要功能,获取垃圾箱的匹配项,取出用过的物品,冲洗并重复

function calc(bins, items) {
    var result = {
            unfilled: bins.slice(),
            unused: items.slice()
        },
        match,
        bin,
        index;

    function reducer2(prev, set) {
        if (!prev) {
            set.length && set.reduce(function (acc, cur) {
                acc += cur;

                return acc;
            }, 0) === bin && (prev = set);
        }

        return prev;
    }

    function remove(item) {
        result.unused.splice(result.unused.indexOf(item), 1);
    }

    for (index = result.unfilled.length - 1; index >= 0; index -= 1) {
        bin = result.unfilled[index];
        match = powerSet(result.unused.slice()).filter(reducer1, {}).reduce(reducer2, '');
        if (match) {
            result[bin] = match;
            match.forEach(remove);
            result.unfilled.splice(result.unfilled.lastIndexOf(bin), 1);
        }
    }

    return result;
}

这些是我们的物品以及它们需要装入的垃圾箱

var array = [6, 5, 7, 8, 6, 12, 16],
    sums = [14, 24, 22];

console.log(JSON.stringify(calc(sums, array)));

输出

{"14":[6,8],"22":[6,16],"24":[5,7,12],"unfilled":[],"unused":[]} 

开启jsfiddle

【讨论】:

  • 这应该比我能给它更多的提升。很遗憾,也许每年有 100 人会看到这个。似乎这是我们拥有众所周知的库的那种事情,令人惊讶的是我们没有。出色的答案,我希望它比我更有帮助。
  • 谢谢,但它仍然是非常“蛮力”。我相信有人可以做得更好。 ;)
  • 由于这是 Vikram Bhat 提到的“np-complete”,你能做的最好的就是有组织的猜测。我越看这个越意识到我别无选择,只能降低期望。在这一点上,我只想要任何可以产生结果的东西,因为这正式是一个不平凡的问题。
【解决方案2】:

展示如何在约束编程系统(此处为 MiniZinc)中对其进行编码可能具有指导意义。

这是完整的模型。它也可以在http://www.hakank.org/minizinc/matching_sums.mzn 获得。

int: n;
int: num_sums;
array[1..n] of int: nums; % the numbers
array[1..num_sums] of int: sums; % the sums

% decision variables

% 0/1 matrix where 1 indicates that number nums[j] is used
% for the sum sums[i]. 
array[1..num_sums, 1..n] of var 0..1: x;

solve satisfy;

% Get the numbers to use for each sum
constraint
   forall(i in 1..num_sums) (
      sum([x[i,j]*nums[j] | j in 1..n]) = sums[i]
   )
;

output 
[
   show(sums[i]) ++ ": " ++ show([nums[j] | j in 1..n where fix(x[i,j])=1]) ++ "\n" 
    | i in 1..num_sums
];

%% Data
n = 6;
num_sums = 3;
nums = [5, 7, 8, 6, 12, 16];
sums = [14, 24, 22];

矩阵“x”是有趣的部分,如果在数字“sums[i]”的和中使用数字“nums[j]”,则 x[i,j] 为 1(真)。

对于这个特定的问题,有 16 种解决方案:

....
14: [8, 6]
24: [8, 16]
22: [6, 16]
----------
14: [6, 8]
24: [6, 5, 7, 6]
22: [6, 16]
----------
14: [6, 8]
4: [5, 7, 12]
22: [6, 16]
----------
14: [6, 8]
24: [6, 6, 12]
22: [6, 16]
----------
14: [6, 8]
24: [8, 16]
22: [6, 16]
----------
...

这些不是不同的解决方案,因为有两个 6。只有一个 6 有 2 个解决方案:

14: [8, 6]
24: [5, 7, 12]
22: [6, 16]
----------
14: [8, 6]
24: [8, 16]
22: [6, 16]
----------

旁白:当我第一次阅读这个问题时,我不确定目标是否是最小化(或最大化)使用的数字。只需一些额外的变量和约束,该模型也可以用于此目的。这是使用最少数字的解决方案:

s: {6, 8, 16}
14: [8, 6]
24: [8, 16]
22: [6, 16]
Not used: {5, 7, 12}

反之,使用的数字的最大计数(这里使用所有数字,因为 6 在“s”中只计算一次):

s: {5, 6, 7, 8, 12, 16}
14: [8, 6]
24: [5, 7, 12]
22: [6, 16]
Not used: {}

扩展的 MiniZinc 模型可在此处获得:http://www.hakank.org/minizinc/matching_sums2.mzn

(Aside2: 一条评论提到了 xkcd 餐厅问题。这是该问题的更通用解决方案:http://www.hakank.org/minizinc/xkcd.mzn。它是当前匹配问题的一个变体,主要区别在于一道菜可以多次计算,而不仅仅是这个匹配问题中的 0..1。)

【讨论】:

  • 我在最初的要求中故意含糊其辞,因为我的关注点非常狭窄,我认为最好提出一个广泛的问题来造福他人。实际上,我正在编写一个脚本,以通过解析一些 csv 文件来匹配销售与存款。将递归遍历日期范围并找到正确的组合以协助协调以弥补一些无法挽回的记录。正如您可能想象的那样,手动猜测会花费不可能的时间。 :)
  • 是的,我注意到了澄清,但我认为优化变体非常整洁。 :-) 顺便说一下,至少有一个 Javascript 包与约束编程系统集成:code.google.com/p/fdcp,它使用 Gecode。但是,我自己还没有测试过(它在我的待办事项清单上)。
  • 对图书馆参考非常有帮助...为了不让 cmets 过于混乱,我只想说我稍后会研究你的答案,因为我已经超出了我的深度这个,万分感谢。 :)
【解决方案3】:

子集和的问题是np完全的但是有一个伪多项式时间动态规划解:-

1.calculate the max element of the sums array
2. Solve it using knapsack analogy
3. consider knapsack capacity = sums[max]
4. items as arr[i] with weight and cost same.
5. maximize profit
6. Check whether a sum can be formed from sums using CostMatrix[sums[i]][arr.length-1]==sums[i]

这是一个相同的java实现:-

public class SubSetSum {
    static int[][] costs;

    public static void calSets(int target,int[] arr) {

        costs = new int[arr.length][target+1];
        for(int j=0;j<=target;j++) {
            if(arr[0]<=j) {

                costs[0][j] = arr[0]; 
            }
        }
        for(int i=1;i<arr.length;i++) {

            for(int j=0;j<=target;j++) {
                costs[i][j] = costs[i-1][j];
                if(arr[i]<=j) {
                    costs[i][j] = Math.max(costs[i][j],costs[i-1][j-arr[i]]+arr[i]);
                }
            }

        }

       // System.out.println(costs[arr.length-1][target]);
       /*if(costs[arr.length-1][target]==target) {
           //System.out.println("Sets :");
           //printSets(arr,arr.length-1,target,"");
       } 

       else System.out.println("No such Set found");*/

    } 

    public static void getSubSetSums(int[] arr,int[] sums) {

        int max = -1;
        for(int i=0;i<sums.length;i++) {
            if(max<sums[i]) {
                max = sums[i];
            }
        }

        calSets(max, arr);

        for(int i=0;i<sums.length;i++) {
            if(costs[arr.length-1][sums[i]]==sums[i]) {
                System.out.println("subset forming "+sums[i]+":");
                printSets(arr,arr.length-1,sums[i],"");
            }
        }




    }

    public static void printSets(int[] arr,int n,int w,String result) {


        if(w==0) {
            System.out.println(result);
            return;
        }

        if(n==0) {
           System.out.println(result+","+arr[0]);
            return; 
        }

        if(costs[n-1][w]==costs[n][w]) {
            printSets(arr,n-1,w,new String(result));
        }
        if(arr[n]<=w&&(costs[n-1][w-arr[n]]+arr[n])==costs[n][w]) {
            printSets(arr,n-1,w-arr[n],result+","+arr[n]);
        }
    }

    public static void main(String[] args) {
        int[] arr = {6, 5, 7, 8, 6, 12, 16};
        int[] sums = {14, 24, 22};        
        getSubSetSums(arr, sums);

    }
}

【讨论】:

  • 这将需要我一些时间来吸收,因为我从来没有接触过 java 并且直到今晚才听说过约束编程 :) 不管我在这个过程中遇到什么,现在 +1。谢谢!
  • 我接受了 Xotic750 的解决方案,因为它是用 javascript 实现的。您的帖子帮助加深了我对问题域的理解,因为这是我第一次在现实世界中介绍。好资料
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 2019-02-24
  • 2018-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2019-02-16
相关资源
最近更新 更多