如果我有一个数组数组和一个总和数组元素的总和列表,那么用于确定总和中包含哪些元素的最有效方法(或者至少不是强力黑客)是什么? / p>
简化示例可能如下所示:
array = [6,5,7,8,6,12,16] sums = [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])
}
我知道总会有至少一个正确的答案,只有我才能检查数字,我不需要将索引配对有重复项,只需要与总数相关的值。是否有解决此类问题的既定功能?
这只是一个javascript问题,因为这是我正在编写解决方案的语言,这更像是通过Javascript过滤的一般数学相关问题。如果这不是合适的论坛,我欢迎重定向到相应的堆栈交换站点。
答案 0 :(得分:2)
好的,诅咒我,这是我的抨击,改进欢迎:)
我认为这是Bin Packing Problem或knapsack 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":[]}
上
答案 1 :(得分: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”是有趣的部分,如果数字“nums [j]”用于数字“sums [i]”的总和,则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,因为这个匹配问题。)
答案 2 :(得分:1)
子集和的问题是np-complete,但是有一个伪多项式时间动态规划解决方案: -
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);
}
}