Skip to content

Instantly share code, notes, and snippets.

@olivierperez
Last active March 28, 2020 12:25
Show Gist options
  • Save olivierperez/d3a8a9918bf586f9cf87a13908889c4b to your computer and use it in GitHub Desktop.
Save olivierperez/d3a8a9918bf586f9cf87a13908889c4b to your computer and use it in GitHub Desktop.
JS Combinations
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))
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