Skip to content

Instantly share code, notes, and snippets.

@Papillard
Created July 17, 2013 14:09
Show Gist options
  • Save Papillard/6020860 to your computer and use it in GitHub Desktop.
Save Papillard/6020860 to your computer and use it in GitHub Desktop.
playing with anagrams..
def combine_anagrams words
hash = Hash.new
words.each do |word|
sorted_word = word.downcase.chars.sort
hash.has_key?(sorted_word) ? hash[sorted_word].push(word) : hash[sorted_word] = [word]
end
hash.values
end
def hashify( string )
# string => hash of letters' occurence
# get rid of non-word chars
hash = Hash.new
string.gsub(/\W/,"").downcase.chars.each {|char| hash[char].nil? ? hash[char] = 1 : hash[char] += 1 }
hash
end
def anagrams? string1, string2
hashify(string1) == hashify(string2)
end
def main
# anagrams grouping
words = %w(cars for potatoes racs Four Scar creams scream)
# => output: [["cars", "racs", "scar"], ["four"], ["for"], ["potatoes"],["creams", "scream"]]
puts combine_anagrams(words)
# clever anagrams
monica = "Monica Lewinsky"
nice_woman = "Nice silky woman"
puts anagrams?( monica, nice_woman )
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment