I've solved a problem that asks you to write a method for determining what words in a supplied array are anagrams and group the anagrams into a sub array within your output.
I've solved it using what seems to be the typical way that you would which is by sorting the words and grouping them into a hash based on their sorted characters.
When I originally started looking for a way to do this I noticed that String#sum
exists which adds the ordinals of each character together.
I'd like to try and work out some way to determine an anagram based on using sum
. For example "cars" and "scar" are anagrams and their sum
is 425.
given an input of %w[cars scar for four creams scream racs]
the expected output (which I already get using the hash solution) is: [[cars, scar, racs],[for],[four],[creams,scream]]
.
It seems like doing something like:
input.each_with_object(Hash.new []) do |word, hash|
hash[word.sum] += [word]
end
is the way to go, that gives you a hash where the values of the key "425" is ['cars','racs','scar']. What I think i'm missing is moving that into the expected format of the output.