Skip to content

Instantly share code, notes, and snippets.

@runlevel5
Created September 3, 2011 18:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save runlevel5/1191557 to your computer and use it in GitHub Desktop.
Save runlevel5/1191557 to your computer and use it in GitHub Desktop.
Anagram Solver
#!/usr/bin/env ruby
# Given a file containing one word per line, print out all the combinations of
# words that are anagrams; each line in the output should contain a set of
# input words that are anagrams of each other. No word should appear in the
# output more than once.
#
# For added programming pleasure, find the longest words that are anagrams,
# and the set of anagrams containing the most words.
module Anagram
def self.extract_words(filename)
@words ||= (File.readlines(filename).collect { |line| line.chomp.downcase }).uniq
end
def self.find_anagrams(words)
@anagram_lengths = Hash.new
@anagram_count = Hash.new
@words_by_anagram ||= words.inject(Hash.new []) do |anagrams, word|
key = word.chars.sort.join
anagrams[key] += word.to_a
@anagram_lengths[key] = key.length
@anagram_count[key] ||= 0
@anagram_count[key] += 1
anagrams
end
end
#def self.get_max_anagram_count
# @anagram_lengths.each do |key, element|
# element.max
# end
#end
end
#driver
if ARGV.size == 1
if File.exists?(ARGV.first.to_s)
@anagram_set = Anagram.find_anagrams(Anagram.extract_words(ARGV.first.to_s))
@anagram_set.each do |key, words|
set = ""
words.each do |word|
set += word + " "
end
puts set + "\n"
end
else
puts 'File not found'
end
else
puts "Usage:\n anna.rb FILENAME"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment