Skip to content

Instantly share code, notes, and snippets.

@ahirschberg
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save ahirschberg/006e9935b82749a43f25 to your computer and use it in GitHub Desktop.

Select an option

Save ahirschberg/006e9935b82749a43f25 to your computer and use it in GitHub Desktop.
all permutations of a list in ruby
def permutations(list)
return [list] if list.size == 1
result = []
list.each do |locked|
list_copy = list.dup
list_copy.delete locked
permutations(list_copy).each do |permutation|
result << permutation.insert(0, locked)
end
end
result # this implicitly returns result. Initially I forgot to add it in and got weird results until I realized this was missing
end
if __FILE__ == $0
p permutations %w[a b c] # %w is ruby shorthand for an array of strings, this example creates the array: ['a', 'b', 'c']
p permutations %w[d e f g]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment