carb0nshel1 - 10 months ago 39

Javascript Question

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 find the lowest possible combination or sum of keys from this array above

`limit`

`result`

A bit of constraints I am trying to work within:

`result`

Such as If

`limit = 0`

`ary[ 0 ]`

`5`

`result`

If

`limit = 11`

`result`

`ary[ 0 ] + ary[ 1 ]`

`15`

`result`

`ary`

`result = 5 + 10 + 28 + 50 + 56 + 280; // equals 429`

`ary[ 0 ]`

My attempts in progress:

`var ary = [5,10,28,50,56,280];`

var limit = 11;

for( var i = 0; i < ary.length; i++ ){

if( ary[ i ] > limit ){

document.write(ary[ i ]);

break;

}

}

Answer Source

- Sort the array
- Do a while loop until the total exceeds the result
- Inside the while loop add all the components in the array until it exceeds the total

```
function calcSumOfLowestComponents(ary,limit){
ary.sort(function(a,b) {
return a - b;
});
var components = [];
var currentTotal = 0;
while (currentTotal <= limit){
for( var i = 0; i < ary.length; i++ ){
currentTotal += ary[ i ];
components.push(ary[ i ]);
if( ary[ i ] + currentTotal > limit ){
break;
}
}
}
return { total : currentTotal, components : components};
}
var array = [5,10,28,50,56,280];
document.write("Total = " + calcSumOfLowestComponents(array,2).total + " Components " + calcSumOfLowestComponents(array,2).components + "</br>");
document.write("Total = " + calcSumOfLowestComponents(array,11).total + " Components " + calcSumOfLowestComponents(array,11).components + "</br>");
document.write("Total = " + calcSumOfLowestComponents(array,28).total + " Components " + calcSumOfLowestComponents(array,28).components + "</br>");
document.write("Total = " + calcSumOfLowestComponents(array,429).total + " Components " + calcSumOfLowestComponents(array,429).components + "</br>");
```

Result

```
Total = 5 Components 5
Total = 15 Components 5,10
Total = 43 Components 5,10,28
Total = 434 Components 5,10,28,50,56,280,5
```