Any possible combination to add up to target in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of unique integers, arr, as the first argument, and target sum as the second argument.

Our function should count the number of all pairs (with repetition allowed) that can add up to the target sum and return that count.

For example, if the input to the function is −

const arr = [1, 2, 3];
const target = 4;

Then the output should be −

const output = 7;

Output Explanation:

Because, the possible combination ways are −

(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Example

The code for this will be −

 Live Demo

const arr = [1, 2, 3];
const target = 4;
const sumUpto = (nums = [], target = 1, map = {}) => {
   if (target === 0){
      return 1;
   };
   if (typeof map[target] != "undefined"){
      return map[target];
   };
   let res = 0;
   for (let i = 0; i<nums.length; i++) {
      if (target >= nums[i]){
         res += sumUpto(nums, target - nums[i], map);
      };
   };
   map[target] = res;
   return res;
};
console.log(sumUpto(arr, target));

Output

And the output in the console will be −

7
raja
Published on 18-Mar-2021 09:03:30
Advertisements