I started with a basic counter that starts at 1 and counts to 300:
for( var i = 1; i <= 300; i++ ){
document.querySelector( 'tbody' ).innerHTML += '<tr><td>' + i + '</td></tr>';
}
html{ font-family:arial } table{ border-collapse:collapse; text-align:center }
td, th{ border:1px solid black; padding:10px }
<table> <thead> <tr> <th>COUNTER</th> </tr> </thead> <tbody></tbody> </table>
I have an array: var ary = [5,10,28,50,56,280]
. As stated in the title I want to find the lowest combination of keys in this array resulting in a sum that also remains above a variable I'll call needle
.
var needle = 0
The next row would look like: | 5 | 25 | 10 + 10 + 5 |.
It's meant to be a simple counter that finds the lowest combination of all keys in an array above the previous value.
I've made some attempts and run into walls every single time. Here was my most recent go at just trying to get all the combinations together but even that fails because it doesn't deal with the possibility of repeated indexs, nor does it increase beyond the max sum of the array:
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>');
}