Skip to content

Instantly share code, notes, and snippets.

@whirlwin
Created May 7, 2012 21:07
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whirlwin/2630436 to your computer and use it in GitHub Desktop.
Save whirlwin/2630436 to your computer and use it in GitHub Desktop.
Simple Ruby script for finding anagrams within a list of words
# 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