I have an array that will always have 6 keys: var ary = [5,10,28,50,56,280]
.
I have a variable defined as limit
I want to check it against.
I want to find the lowest possible combination or sum of keys from this array that is above limit
. We'll call this result
.
A bit of constraints I am trying to work within:
1 result
can be a single key itself:
Such as If limit = 0
the lowest possible combination or sum of keys should default to the lowest key it can find which would be ary[ 0 ]
. in this case or 5
.
2 result
can be a combination of any keys:
If limit = 11
, result
would = ary[ 0 ] + ary[ 1 ]
( 5 + 10 ). which would be 15
.
3 And lastly, result
can be above the greatest sum of ary
:
result = 5 + 10 + 28 + 50 + 56 + 280; // equals 429
In this case limit would be 430
Note: Any key can be repeated as many times as it has to before it surpasses result
.
My attempts in progress:
function add(a, b) { //add all keys in array
return a + b;
}
var combine = function(a, min) { //find all combinations of array
var fn = function(n, src, got, all) {
if (n == 0) {
if (got.length > 0) {
all[all.length] = got;
}
return;
}
for (var j = 0; j < src.length; j++) {
fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
}
return;
}
var all = [];
for (var i = min; i < a.length; i++) {
fn(i, a, [], all);
}
all.push(a);
return all;
}
var subsets = combine([5,10,28,50,56,280], 1);
var limit = 11;
for( var i = 0; i < subsets.length; i++ ){
document.write('combination: ' + subsets[ i ] + ' sum: ' + subsets[ i ].reduce(add, 0) + '<br>');
}