- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Generating desired combinations in JavaScript
The function should find all possible combinations of m numbers that add up to a number n,given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
For example − If the inputs are −
const m = 3, n = 4;
Then the output should be −
const output = [ [1, 2, 4] ];
If the inputs are −
const m = 3, n = 9;
Then the output should be −
const output = [ [1, 2, 6], [1, 3, 5], ];
Example
The code for this will be −
const m = 3, n = 9; const findSum = (m, n) => { const search = (from, prefix, m, n) => { if (m === 0 && n === 0) return res.push(prefix); if (from > 9) return; search(from + 1, prefix.concat(from), m − 1, n − from); search(from + 1, prefix, m, n); }; const res = []; search(1, [], m, n); return res; }; console.log(findSum(m, n));
Output
And the output in the console will be −
[ [ 1, 2, 6 ], [ 1, 3, 5 ], [ 2, 3, 4 ] ]
- Related Articles
- Generating desired pairs within a range using JavaScript
- Generating combinations from n arrays with m elements in JavaScript
- Triplet with desired sum in JavaScript
- Generating Random Prime Number in JavaScript
- Generating random hex color in JavaScript
- Finding three desired consecutive numbers in JavaScript
- Binary subarrays with desired sum in JavaScript
- Using operations to produce desired results in JavaScript
- Finding desired numbers in a sorted array in JavaScript
- Generating all possible permutations of array in JavaScript
- Generating random string of specified length in JavaScript
- Check if string ends with desired character in JavaScript
- All combinations of sums for array in JavaScript
- Generate all combinations of supplied words in JavaScript
- Find all substrings combinations within arrays in JavaScript

Advertisements