Last active
March 28, 2020 12:25
-
-
Save olivierperez/d3a8a9918bf586f9cf87a13908889c4b to your computer and use it in GitHub Desktop.
JS Combinations
This file contains hidden or 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
const computeCombinations = (items) => { | |
let doIt = (rest, start, output) => { | |
if (rest.length == 0) { | |
output.push(start) | |
return | |
} | |
for (let i=0; i < rest.length; i++) { | |
let begin = rest.slice(0, i) | |
let end = rest.slice(i+1) | |
let pick = rest[i] | |
let newStart = Array.from(start) | |
newStart.push(pick) | |
doIt(begin.concat(end), newStart, output) | |
} | |
} | |
let output = [] | |
doIt(items, [], output) | |
return output | |
} | |
const cards = [1,2,3] | |
let combinations = computeCombinations(cards) | |
console.log('Number of combinations: ' + combinations.length) | |
combinations.forEach(deck => console.log(deck)) |
This file contains hidden or 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
Number of combinations: 6 | |
[ 1, 2, 3 ] | |
[ 1, 3, 2 ] | |
[ 2, 1, 3 ] | |
[ 2, 3, 1 ] | |
[ 3, 1, 2 ] | |
[ 3, 2, 1 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment