Skip to content

Instantly share code, notes, and snippets.

@higuma
Last active December 18, 2015 13:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save higuma/9889266 to your computer and use it in GitHub Desktop.
Save higuma/9889266 to your computer and use it in GitHub Desktop.
CoffeeScript Array permutation generator
# 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