Creating permutations to reach a target number, but reuse the provided numbers JavaScript


We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a target sum Number as the second argument.

The function should return an array of all those subarrays from the original array whose elements sum to make the target sum. We can use a single number twice to achieve the sum.

For example −

If the input array and number are −

const arr = [1, 2, 4];
const sum = 4;

then the output should be −

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

Example

const arr = [1, 2, 4];
const sum = 4;
const getCombinations = (arr = [], sum) => {
   const result = [];
   const pushElement = (i, t) => {
      const s = t.reduce(function (a, b) {
      return a + b;
      }, 0);
      if (sum === s) {
         result.push(t);
         return;
      };
      if (s > sum || i === arr.length) {
         return;
      };
      pushElement(i, t.concat([arr[i]]));
      pushElement(i + 1, t);
   }
   pushElement(0, []);
   return result;
};
console.log(getCombinations(arr, sum));

Output

And the output in the console will be −

[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 4 ] ]

Updated on: 21-Nov-2020

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements