To find if two words are anagrams of each other, do this:
sort(word1) == sort(word2)
done.
The trick is knowing that an anagram has a signature, and that signature can be found if you sort a word's characters alphabetically. Then you do the same to the other word and compare both of their signatures together. Voilá.
"genuine class" == "alec guinness"
because
"aceegilnnssu" == "aceegilnnssu"
In Ruby you'd write your own alphabetic sorting function first, then apply it to each word. def sortAZ (word)
word.downcase.unpack("c*").sort.pack("c*")
end
def is_anagram (word1, word2)
sortAZ(word1) == sortAZ(word2)
end
puts "is_anagram(ARGV[1], ARGV[2])"
I recall seeing this trick in a Ruby book (probably PickAxe or something) and thought it was cool because I had never thought about finding an anagram in this way. Regardless, it stuck with me so, if this was asked in an interview, I'd be able to answer the question easily and look like a rockstar...when really it's just knowledge that stuck with me.By the way, the alphabetic sorting here is done by unpacking each character into its number representation and then sorting the resulting numbers.