Computer >> Computer tutorials >  >> Programming >> Javascript

Generating desired combinations in JavaScript


The function should find all possible combinations of m numbers that add up to a number n,given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

For example − If the inputs are −

const m = 3, n = 4;

Then the output should be −

const output = [
   [1, 2, 4]
];

If the inputs are −

const m = 3, n = 9;

Then the output should be −

const output = [
   [1, 2, 6],
   [1, 3, 5],
];

Example

The code for this will be −

const m = 3, n = 9;
const findSum = (m, n) => {
   const search = (from, prefix, m, n) => {
      if (m === 0 && n === 0) return res.push(prefix);
      if (from > 9) return;
      search(from + 1, prefix.concat(from), m − 1, n − from);
      search(from + 1, prefix, m, n);
   };
   const res = [];
   search(1, [], m, n);
   return res;
};
console.log(findSum(m, n));

Output

And the output in the console will be −

[ [ 1, 2, 6 ], [ 1, 3, 5 ], [ 2, 3, 4 ] ]