Ways to get to a specific sum in JavaScript


Problem

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

For each Integer in the array, our function can either assign ‘+’ or ‘-’ to it.

Our function should find out how many ways in total exist to assign ‘+’, ‘-’ to make the sum of integers of the array equal to the target sum, target.

For example, if the input to the function is −

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

Then the output should be −

const output = 5;

Output Explanation:

Because the 5 ways are −

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

Example

The code for this will be −

 Live Demo

const arr = [1, 1, 1, 1, 1];
const target = 3;
const waysToSum = (arr = [], target = 1) => {
   const map = {};
   const find = (arr, target, i) => {
      let val = i + '->' + target;
      if(map[val] !== undefined){
         return map[val];
      };
      if(i === 0){
         if (target === 0 && arr[0] === 0) { return 2 }
         return arr[0] === target || arr[0] === -target ? 1 : 0
      };
      map[val] = find(arr, target + arr[i], i - 1) + find(arr, target - arr[i], i - 1);
      return map[val]
   };
   return find(arr, target, arr.length-1)
};
console.log(waysToSum(arr, target));

Output

And the output in the console will be −

5

Updated on: 04-Mar-2021

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements