Skip to content

Instantly share code, notes, and snippets.

@talum
Created November 28, 2019 21:30
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 talum/85f722a84f361d19e0aef750a3874825 to your computer and use it in GitHub Desktop.
Save talum/85f722a84f361d19e0aef750a3874825 to your computer and use it in GitHub Desktop.
Combinations in JS
// return all combinations of array elements for size n
// ex) combinations([1,2,3], 2) => [[1,2], [2,3], [1,3]]
// use backtracking & recursion
// iteration: for each element
// add element
// recurse with element
// remove element
// continue
function combinations(array, size) {
let combos = [];
function helper(chunk, n) {
if (chunk.length == size) {
combos.push(chunk.slice());
return;
}
for(let i = n; i < array.length; i++) {
chunk.push(array[i]);
helper(chunk, i+1);
chunk.pop();
}
}
helper([], 0);
return combos;
}
let result = combinations([1,2,3,4], 3);
console.log(result);
@talum
Copy link
Author

talum commented Sep 30, 2021

Comments on Gists are cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment