Created
October 31, 2017 13:25
-
-
Save vindia/a514711f84e5b52a914fb0c9e4665eae to your computer and use it in GitHub Desktop.
Find anagrams in Ruby
This file contains hidden or 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
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