Created
May 7, 2012 21:07
-
-
Save whirlwin/2630436 to your computer and use it in GitHub Desktop.
Simple Ruby script for finding anagrams within a list of words
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
# encoding: utf-8 | |
# Simple Ruby script for finding anagrams in a list | |
# Tested with ruby 1.9.3 | |
words = ['alt', 'altfor', 'andre', 'at', 'bar', 'bra', 'bry', 'byr', 'dem', | |
'den', 'denne', 'dra', 'drev', 'drikke', 'dro', 'ende', 'enden', 'engang', | |
'ens', 'etter', 'gangen', 'gift', 'gikk', 'gilde', 'hellestein', 'hun', 'hus', | |
'kisten', 'krok', 'lovt', 'lysnet', 'lysten', 'løst', 'med', 'mor', 'navn', | |
'ned', 'nede', 'niste', 'ord', 'ordet', 'rad', 'rette', 'ristet', 'rod', 'rokk', | |
'rom', 'rå', 'sen', 'sitter', 'skinte', 'steinhelle', 'stien', 'stuen', 'støl', | |
'suten', 'søsteren', 'søstrene', 'ta', 'tolv', 'torde', 'truet', 'turte', | |
'vann', 'år'] | |
# Anagrams are equal when all characters are sorted | |
words_hash = words.each_with_object(Hash.new []) do |word, hash| | |
hash[word.chars.sort] += [word] | |
end | |
# Print the anagrams | |
words_hash.each do |word, matching_words| | |
puts matching_words.join ', ' if matching_words.length > 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment