Skip to content

Instantly share code, notes, and snippets.

@malandrina
Created September 19, 2012 22:24
Show Gist options
  • Save malandrina/3752723 to your computer and use it in GitHub Desktop.
Save malandrina/3752723 to your computer and use it in GitHub Desktop.
Writing a faster anagram solver for same-length anagrams, in Ruby

Writing a faster anagram solver for same-length, one-word anagrams, in Ruby

In [my first attempt] (https://gist.github.com/3745321) at writing an anagram solver, I stored my word list in a hash in which values are words and keys are characters in those words, sorted alphabetically.

I liked this approach, but my implementation was not ideal: I defined the creation of the hash as an activity that occurs when the #same_length_anagrams method is called. This, of course, made it super slow!

This time I was able to structure things so that the word list hash is created when the program is initialized. The Ruby documentation for the #shell class leaves a lot to be desired, but [this very helpful blog post] (http://devver.wordpress.com/2009/10/12/ruby-subprocesses-part_3/) on starting sub-processes in Ruby provided me with a great point of departure. My next step is to figure out how to clean up lines 1 - 12.

# Create word list hash
require 'shell'

Shell.def_system_command :ruby
shell = Shell.new
input = File.open('wordlist.txt').read.split(/\n/)
process = shell.transact do
		Hash[input.map { |x| [x.upcase, x.chars.to_a.sort.join.upcase] }]
	end
output = process.group_by { |key, value| process[key] }
output = output.each_pair do |key, value|
	output[key] = value.transpose.delete_at(0)
end

# Define method for finding same-length anagrams
def same_length_anagrams(word, word_list)
	word_chars = word.chars.to_a.sort.join.upcase
	puts word_list[word_chars] == nil ? "Sorry! No anagrams found." : word_list[word_chars]
	puts "\n"
end

# Provide a simple UI/instructions
puts "*** Enter some characters to be anagrammed!
	  Press Ctrl + C to exit. ***"
loop do
	same_length_anagrams(gets.chomp, output)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment