Last active
December 18, 2015 13:02
-
-
Save higuma/9889266 to your computer and use it in GitHub Desktop.
CoffeeScript Array permutation generator
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
# internal: generate permutation recursively | |
generatePermutation = (perm, pre, post, n) -> | |
if n > 0 | |
for i in [0...post.length] | |
rest = post.slice 0 | |
elem = rest.splice i, 1 | |
generatePermutation perm, pre.concat(elem), rest, n - 1 | |
else | |
perm.push pre | |
return | |
### | |
extend Array.prototype | |
e.g. [0, 1, 2].permutation(2) | |
=> [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]] | |
### | |
Array::permutation = (n = @.length) -> | |
perm = [] | |
generatePermutation perm, [], @, n | |
perm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment