 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Any possible combination to add up to target in JavaScript
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 −
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
Advertisements
 