Skip to content

Instantly share code, notes, and snippets.

@zoubin
Created June 7, 2017 06:59
Show Gist options
  • Save zoubin/7460563eaf14ba45a0053ac7fbcd3e37 to your computer and use it in GitHub Desktop.
Save zoubin/7460563eaf14ba45a0053ac7fbcd3e37 to your computer and use it in GitHub Desktop.
How to exhaust all permutations of an array of elements
function * permutation (input) {
let n = input.length
if (n === 0) {
yield []
} else {
let needle = input.pop()
for (let p of permutation(input)) {
for (let i = 0; i < n; i++) {
let q = p.slice()
q.splice(i, 0, needle)
yield q
}
}
}
}
/*
for (let p of permutation([1,2,3,4])) {
console.log(p)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment