Created
October 7, 2015 16:20
-
-
Save acapilleri/f5081c366034e690b1d1 to your computer and use it in GitHub Desktop.
Permutations in Ruby from scratch
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 get_perm str | |
return [str] if str.size == 1 | |
perms = [] | |
first_char = str.slice!(0) | |
words = get_perm(str) | |
words.each do |word| | |
perms += insert_each(first_char, word) | |
end | |
perms | |
end | |
def insert_each char, str | |
results = [] | |
size = str.size-1 | |
results << char + str | |
for i in (0..size) | |
results << str[0..i] + char + str[i+1..size] | |
end | |
results | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment