
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
Create Permutations to Reach a Target Number in JavaScript
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 ] ]
Advertisements