Skip to content

Instantly share code, notes, and snippets.

@vindia
Created October 31, 2017 13:25
Show Gist options
  • Save vindia/a514711f84e5b52a914fb0c9e4665eae to your computer and use it in GitHub Desktop.
Save vindia/a514711f84e5b52a914fb0c9e4665eae to your computer and use it in GitHub Desktop.
Find anagrams in Ruby
require "benchmark"
time = Benchmark.measure do
words = File.read("wordlist.txt").downcase.split("\n")
anagrams = Hash.new{|hash, key| hash[key] = []}
words.each do |word|
root = word.chars.sort.join
anagrams[root] << word
end
anagrams.select{|_,w| w.uniq.size > 1}.each do |_, words|
puts "#{words.shift} is anagram of #{words.uniq.join(', is anagram of ')}"
end
end
puts time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment