Created
June 7, 2017 06:59
-
-
Save zoubin/7460563eaf14ba45a0053ac7fbcd3e37 to your computer and use it in GitHub Desktop.
How to exhaust all permutations of an array of elements
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
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