Skip to content

Instantly share code, notes, and snippets.

@vasanthv
Created March 12, 2018 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasanthv/3205a73a32417748325f8f9e4f802b39 to your computer and use it in GitHub Desktop.
Save vasanthv/3205a73a32417748325f8f9e4f802b39 to your computer and use it in GitHub Desktop.
The function returns all possible combinations of a given number represented as array.
//Based on https://stackoverflow.com/a/46880431/607608
function getComb(set, val) {
const res = [];
function comb(set, k, partial, pref) {
if (!partial) partial = [];
for (const element in set) {
if (k > 1) {
const set_copy = set.slice();
set_copy.splice(element, 1);
comb(set_copy, k - 1, partial.concat([set[element]]));
}else {
const nextVal = +(partial.concat(set[element]).join(''));
res.push(nextVal);
};
}
}
comb(set.sort(), set.length);
return res;
}
console.log(getComb([3,9,5,2]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment