I have a written exam here, here's the instruction.
Write a program that prints out groups of words that are anagrams. Anagrams are words that have the same exact letters in them but in a different order. Your output should look something like this:
["demo", "dome", "mode"]
["neon", "none"]
(etc)
And here's the solution for this:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
result = {}
words.each do |word|
key = word.split('').sort.join
if result.has_key?(key)
result[key].push(word)
else
result[key] = [word]
end
end
result.each do |k, v|
puts "------"
p v
end
I've been trying to understand the ruby code solution but can't easily grasp it. One of my question is how can you test the result hash if it has no key or any element contain from it. Another thing how does the .join and .sort works on this code.
I am really confuse how it all go thru the answer. Can somebody out there can explain on this codes line by line in a layman's term a beginner who is a dummy like me can understand?
I would just do this:
words = ['demo', 'none', 'tied', 'evil', 'dome', 'mode', 'live',
'fowl', 'veil', 'wolf', 'diet', 'vile', 'edit', 'tide',
'flow', 'neon']
words.group_by { |word| word.chars.sort }.values
#=> [["demo","dome","mode"],["none","neon"],["tied","diet","edit","tide"],["evil","live","veil","vile"],["fowl","wolf","flow"]]
I will explain the code for you.
key = word.split('').sort.join
This will create array of characters from string, sort the letters alphabetically and then join the characters into new string. This way, key for the hash is created.
For example word "mode" will be transformed to array ['m', 'o', 'd', 'e'], than sorted ['d', 'e', 'm', 'o'] so the final key string will be "demo". This way words "mode" and "demo" will have the same key in the hash.
if result.has_key?(key)
result[key].push(word)
else
result[key] = [word]
end
If branch of the condition checks if hash has the given key and if it does it adds the word to the array. Otherwise it will assign array with just the word to the key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With