Last active
August 29, 2015 14:17
-
-
Save ahirschberg/006e9935b82749a43f25 to your computer and use it in GitHub Desktop.
all permutations of a list in ruby
This file contains hidden or 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
| 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