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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ] ]
raja
Updated on 21-Nov-2020 06:49:10

Advertisements