Last active
December 24, 2015 18:19
-
-
Save royzinn/6842266 to your computer and use it in GitHub Desktop.
Anagram with Hash#inject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# taking a list of words (space delimited) and groups them if they're anagrams | |
# example input: star mary demo hops rats posh tars mode else army shop demo will return: | |
# "rats star tars" | |
# "army mary" | |
# "demo demo mode" | |
# "hops posh shop" | |
# "else" | |
def anagrams | |
words = gets.chomp.split | |
anagrams_hash = words.inject({}) {|h,w| h[w.chars.sort.join] ? h[w.chars.sort.join] << w : h[w.chars.sort.join] = [w]; h} | |
anagrams_hash.each {|k,v| p v.sort.join(" ")} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment