0

In var ary = [5,10,28,50,56,280] I want to try all combinations or subsets of this array until I exceed a limit.

I want to save that limit in a variable and push all the addends into an array.

var ary = [5,10,28,50,56,280];
var limit = 11;
var result = [];
var addends = [];


for( var i = 0; i <= ary.length; i++ ){
  if( ary[ i ] > limit ){
    result.push( ary[ i ] );
    addends.push( ary[ i ] );
  }
  else if( ary[ i ] + ary[ i ] > limit ){
    result.push( ary[ i ] + ary[ i ] )
    addends.push( ary[ i ] );
    addends.push( ary[ i ] );
  }
}

How would I do this systematically regardless of array size or limit value?

  • a limit of what kind? – Bálint Oct 25 '16 at 21:16
  • What's wrong with your current solution? – Mike Cluck Oct 25 '16 at 21:16
  • @Bálint the limit is just a variable I want to exceed using combinations of sums from the keys in my array. I'll update my question. This is a smaller step to my bigger question here: http://stackoverflow.com/questions/40230336/how-to-find-the-lowest-possible-combination-of-keys-within-an-array –  Oct 25 '16 at 21:18
  • @MikeC My code isn't really a solution because it isn't exhaustive. I'm hoping for a way to try all combinations of the indexes in my array until I exceed the `limit`. This question is a smaller step to this http://stackoverflow.com/questions/40230336/how-to-find-the-lowest-possible-combination-of-keys-within-an-array –  Oct 25 '16 at 21:22
  • You can use the Compound Assignment operator `+=` to add an array key to itself –  Oct 25 '16 at 21:49

1 Answers1

0

I assume you want to test all permutations:

function permutator(inputArr) {
  var results = [];

  function permute(arr, memo) {
    var cur, memo = memo || [];

    for (var i = 0; i < arr.length; i++) {
      cur = arr.splice(i, 1);
      if (arr.length === 0) {
        results.push(memo.concat(cur));
      }
      permute(arr.slice(), memo.concat(cur));
      arr.splice(i, 0, cur[0]);
    }

    return results;
  }    
  return permute(inputArr);
}

var permutations= permutator([5,10,28,50,56,280]);
console.log(permutations);

Given this, you should be able to add code to deal with your vague comment about a "limit".

This code was stolen without shame from @delimited here: Permutations in JavaScript?

Community
  • 1
  • 1
Steve H.
  • 6,912
  • 2
  • 30
  • 49
  • Did you answer your own question? See, for example: http://stackoverflow.com/questions/8822950/creating-combinations-in-javascript and add the code to reject the ones that sum over your limit. – Steve H. Oct 25 '16 at 21:48