aris
October 10, 2012, 6:40pm
1
Hi,
I am new to Ruby and am working on Anagram. So in anagram for the input
below
input: [‘cars’, ‘four’,‘scar’, ‘creams’, ‘scream’, ‘scream’]
I want an output like this
output: [ [“cars”,“scar”],
[“four”],
[“creams”, “scream”, “scream”] ]
But i am getting an output like
output: [ [“cars”,“scar”],
[“four”],
[“creams”, “scream”] ]
because of Hash property.
This is my code.
sorted_words = Hash.new(0)
words.each { |word| sorted_words[word]=word.downcase.chars.sort { |a, b|
a.casecmp(b) }.join
}
sorted_hash = {}
sorted_words.each_pair do |key, value|
(sorted_hash[value] ||= []) << key
end
anagram_array = sorted_hash.values
Please advice me (with some code) how to solve this. Thankyou for taking
you time out and helping with this amazing language
maybe like this?
words.uniq.group_by{|w| w.downcase.each_char.sort}.values
Hans M. wrote in post #1079264:
maybe like this?
words.uniq.group_by{|w| w.downcase.each_char.sort}.values
Thank you Hans for such a quick reply. Two things, where should this
line go and can you explain this a bit that how does this solve the
problem
this line replaces all your other posted lines.
so you have this:
anagram_array = words.uniq.group_by{|w|
w.downcase.each_char.sort}.values
uniq removes the second scream
group_by wants a block
w.downcase.each_char.sort makes an array of chars so “Cars” will be
turned to [“a”,“c”,“r”,“s”]
so we have:
{
[“a”, “c”, “r”, “s”]=>[“cars”, “scar”],
[“f”, “o”, “r”, “u”]=>[“four”],
[“a”, “c”, “e”, “m”, “r”, “s”]=>[“creams”, “scream”]
}
but you only want the values, so i add .values
Hans M. wrote in post #1079276:
this line replaces all your other posted lines.
so you have this:
anagram_array = words.uniq.group_by{|w|
w.downcase.each_char.sort}.values
uniq removes the second scream
group_by wants a block
w.downcase.each_char.sort makes an array of chars so “Cars” will be
turned to [“a”,“c”,“r”,“s”]
so we have:
{
[“a”, “c”, “r”, “s”]=>[“cars”, “scar”],
[“f”, “o”, “r”, “u”]=>[“four”],
[“a”, “c”, “e”, “m”, “r”, “s”]=>[“creams”, “scream”]
}
but you only want the values, so i add .values
Thanks, i removed uniq and did what you said and got exactly what i was
looking for. This is soo cool i never thought that only a line could be
soo powerful