Created
August 17, 2012 13:24
-
-
Save ltello/3378668 to your computer and use it in GitHub Desktop.
Anagram count
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
# Given a list of words, return a hash with the anagram counting | |
class String | |
# Returns the associated anagram (string with the same letters sorted) | |
# Ex: "accb".anagram # => "abcc" | |
def anagram | |
split('').sort.join | |
end | |
end | |
class Hash | |
# Returns a new hash with the same keys but the count of values in each value as value | |
# Ex: {:a => [1,2,3], :b => 'x'}.to_values_count # => {:a => 3, :b => 1} | |
def to_values_count | |
inject({}) do |result, key_value_pair| | |
result.merge!(key_value_pair.first => Array(key_value_pair.last).size) | |
end | |
end | |
# Bang version of to_values_count | |
def to_values_count! | |
each {|k, v| merge!(k => Array(v).size)} | |
end | |
end | |
words = %w(abb bba aba bba abb aab abc bab) | |
words.group_by(&:anagram).to_values_count # => {"abb" => 5, "aab" => 2, "abc" => 1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment