Skip to content

Instantly share code, notes, and snippets.

@kwleland
Created December 13, 2013 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwleland/7947098 to your computer and use it in GitHub Desktop.
Save kwleland/7947098 to your computer and use it in GitHub Desktop.
same as bm_word_anagrams.rb without the benchmark
# Word anagrams (with duplicates).
# Submitted by Giovanni Intini <intinig@gmail.com>
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