anagrams in ruby

Ruby Kata Six -- Anagram

# This was a fun one; another classic algorithm popular in class but always # fun to recreate. This reminds me also of the related Boggle type problem. # Here's my answer for the anagram list. Just feed the list of words to stdin. #!/usr/bin/env ruby def toHistogram (str) res = [ ] str.each_byte { |i| res << i } res.sort end result = STDIN.readlines.inject({}) do |n, w| w.chomp! h = toHistogram(w) n[h] ||= [ ] n[h].push(w) n end goodkeys = result.keys.sort_by { |i| -result[i].size } goodkeys.each { |k| v = result[k] puts v.join(' ') if v.size > 1 }

About this entry