Skip to content

Instantly share code, notes, and snippets.

@davidchambers
Created October 27, 2013 18:25
Show Gist options
  • Save davidchambers/7186099 to your computer and use it in GitHub Desktop.
Save davidchambers/7186099 to your computer and use it in GitHub Desktop.
concat = (lists...) ->
[].concat(lists...)
_traverse = (list, path, f) ->
if list.length is 0
f(path)
else
for item, idx in list
_traverse(concat(list.slice(0, idx), list.slice(idx + 1)),
concat(path, [item]), f)
traverse = (list, f) ->
_traverse(list, [], f)
traverse(['foo', 'bar', 'baz', 'quux'], (path) -> console.log(path.join(' > ')))
@davidchambers
Copy link
Author

$ coffee permutations.coffee
foo > bar > baz > quux
foo > bar > quux > baz
foo > baz > bar > quux
foo > baz > quux > bar
foo > quux > bar > baz
foo > quux > baz > bar
bar > foo > baz > quux
bar > foo > quux > baz
bar > baz > foo > quux
bar > baz > quux > foo
bar > quux > foo > baz
bar > quux > baz > foo
baz > foo > bar > quux
baz > foo > quux > bar
baz > bar > foo > quux
baz > bar > quux > foo
baz > quux > foo > bar
baz > quux > bar > foo
quux > foo > bar > baz
quux > foo > baz > bar
quux > bar > foo > baz
quux > bar > baz > foo
quux > baz > foo > bar
quux > baz > bar > foo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment