Created
November 28, 2019 21:30
-
-
Save talum/85f722a84f361d19e0aef750a3874825 to your computer and use it in GitHub Desktop.
Combinations in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Comments on Gists are cool!