Created
July 28, 2014 14:17
-
-
Save amnn/0eec48c45d12c887219f to your computer and use it in GitHub Desktop.
Solution to http://codekata.com/kata/kata06-anagrams/
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
require 'set' | |
class AnagramDict | |
include Enumerable | |
def initialize | |
@dict = {} | |
end | |
def put(word) | |
(@dict[key word] ||= Set[]) << word | |
end | |
def set_count | |
@dict.count | |
end | |
def each(&blk) | |
@dict.each(&blk) | |
end | |
private | |
def key(word) | |
word.chars.sort.join | |
end | |
end | |
anagrams = AnagramDict.new | |
File.open('./wordlist.txt').each do |line| | |
anagrams.put(line.chomp) | |
end | |
puts "Sets: #{anagrams.set_count}" | |
most_similar = | |
anagrams.max_by { |(_, words)| words.count }.last | |
puts "Largest set: #{most_similar.to_a.join(' ')}" | |
longest = | |
anagrams | |
.select { |(_, words)| words.count > 2 } | |
.max_by { |(key, _)| key.length }.last | |
puts "Longest anagram: #{longest.to_a.join(' ')}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment