0

If we start with array [1, 2, 3, 4] and getting the following result:

letresult = [[1],[2],[3],[4],[1,2],[1,3],[1,4],[2,3],[2,4],[3,4],[1,2,3],[2,3,4],[1,2,3,4]];

So that later you can find the most suitable variant of the sum of the numbers in the array according to the specified condition (for example, no more than 8)

I don't understand how to generate all possible combinations from array [1,2,3,4] to get result I wrote above. Or if i have not only 4 numbers in array but [1,2,3,....,9,10] and how to generate all possible 3 digit numbers.

const findNumber = function(z, array) {
  let sum = [];

  for (let i = 0; i < array.length; i++) {
    let reducer = array[i].reduce((a, b) => a + b);
    if (reducer < z) {
      sum.push(reducer)
    }
  }
  let max = Math.max.apply(Math, sum);
  console.log(sum);
  console.log(max);
  console.log('index in array ', sum.indexOf(max))
}
findNumber(8, [
  [1],
  [2],
  [3],
  [4],
  [1, 2],
  [1, 3],
  [1, 4],
  [2, 3],
  [2, 4],
  [3, 4],
  [1, 2, 3],
  [2, 3, 4],
  [1, 2, 3, 4]
]);
mplungjan
  • 155,085
  • 27
  • 166
  • 222
  • maybe consult the answers to this question: https://stackoverflow.com/questions/5752002/find-all-possible-subset-combos-in-an-array – Manu Oct 11 '21 at 13:11

0 Answers0