Javascript, all possible sums of an array members (up to 4)

后端 未结 2 997
盖世英雄少女心
盖世英雄少女心 2021-01-06 05:36

I am unable to figure out how to write a function that will calculate all possible sums of of the elements of an array, with a max of 4 elements per addition.

Given<

2条回答
  •  天涯浪人
    2021-01-06 06:10

    jsFiddle Demo

    You can use a permutation subset recursive algorithm to find the set of all of the sums and also their combinations.

    var x = [1, 32, 921, 9213, 97, 23, 97, 81, 965, 82, 965, 823];
    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;}));
    //log sums without sort to have them line up to sets or modify previous structure
    console.log(sets);

提交回复
热议问题