- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements