Skip to content

Instantly share code, notes, and snippets.

@thejsj
Last active January 23, 2017 00:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thejsj/3005944d545b227eef8c75b259f7eae4 to your computer and use it in GitHub Desktop.
Save thejsj/3005944d545b227eef8c75b259f7eae4 to your computer and use it in GitHub Desktop.
All permutations for an array
// http://stackoverflow.com/a/22063440/2684055
function allPermutations (arr) {
function permutate (res, value, key, arr) {
if (arr.length <= 1) return [value]
// Eliminate current value
let result = arr.slice(0, key).concat(arr.slice(key + 1))
.reduce(permutate, [])
.map(perm => [value].concat(perm))
return res.concat(result)
}
return arr.reduce(permutate, [])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment