Created
December 13, 2013 16:38
-
-
Save kwleland/7947098 to your computer and use it in GitHub Desktop.
same as bm_word_anagrams.rb without the benchmark
This file contains 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
# Word anagrams (with duplicates). | |
# Submitted by Giovanni Intini <[email protected]> | |
class String | |
def swap(i) | |
tmp = self[0,1] | |
self[0] = self[i] | |
self[i] = tmp | |
self | |
end | |
def permutations | |
return [self] if size == 1 | |
results = [] | |
tmp = self | |
size.times do |pos| | |
tmp.swap(pos) | |
partial_results = tmp[1..-1].permutations | |
partial_results.each_index do |i| | |
partial_results[i] = tmp[0,1] + partial_results[i] | |
end | |
results << partial_results | |
end | |
results.flatten | |
end | |
end | |
puts "alongword".permutations.size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment