-3

In jquery, how to get all the possibles sums in an array ?

For example, if I had an array like this : [ 2 , 3 , 8 ]

I would have a result like this : [ 2 , 3 , 5 , 8 , 10 , 11 , 13 ]

...which corresponds to 2+3 , 2+8 , 3+8, 2+3+8, and the solos 2,3,8.

Thanks. Nicolas.

  • 3
    this is not hard to research or to figure out... please show what you tried. We aren't here to do your homework for you – charlietfl Oct 12 '15 at 17:29

1 Answers1

0

Try Travis J's solution

JSFiddle

var x = [2, 3, 8];
var sums = [];
var sets = [];
function SubSets(read, queued)
{
    if( read.length == 4 || (read.length <= 4 && queued.length == 0) )
    {
        if( read.length > 0 ){
        var total = read.reduce(function(a,b){return a+b;},0);
        if(sums.indexOf(total)==-1){
        sums.push(total);
        sets.push(read.slice().sort());
        }
        }
    }
    else
    {
        SubSets(read.concat(queued[0]),queued.slice(1));
    SubSets(read,queued.slice(1));
    }
}
SubSets([],x);
console.log(sums.sort(function(a,b){return a-b;}));
Community
  • 1
  • 1
abagh0703
  • 841
  • 1
  • 12
  • 26