Skip to content

Instantly share code, notes, and snippets.

@nathanallen
Last active December 21, 2015 18:48
Show Gist options
  • Save nathanallen/6349394 to your computer and use it in GitHub Desktop.
Save nathanallen/6349394 to your computer and use it in GitHub Desktop.
Refactored Anagram Server
class CreateWords < ActiveRecord::Migration
def change
create_table :words do |t|
t.string :word
t.string :sorted_letters
t.integer :length
end
end
end
class CreateAnagrams < ActiveRecord::Migration
def change
add_index :words, :sorted_letters
remove_column :words, :length
create_table :sorted_letters do |t|
t.string :sorted
t.string :anagrams, default: ""
t.integer :count, default: 0
end
add_index :sorted_letters, :sorted
add_index :sorted_letters, :count
end
end
<div class="container">
<h1>Anagram Finder</h1>
<form action="/" method="get">
<% if @input == nil %>
Find an anagram:
<% else %>
Find another anagram:
<% end %>
<br>
<input type="text" name="input">
<input type="submit" value="Submit">
</form>
</div>
<% unless @input == nil %>
<div class="container">
Here are all the anagrams for <%= @input.to_s %>:
<ul><% if @anagrams %>
<% @anagrams.each do |w| %>
<li><%= w %></li>
<% end %>
<% end %>
<% end %>
</ul>
</div>
get '/' do
@input = params[:input]
unless @input == nil
@anagrams = Word.anagrams(@input)
end
erb :index
end
File.open('/usr/share/dict/words').each do |word|
Word.create!(word: word.chomp, sorted_letters: word.chomp.split('').sort.join)
end
Word.all.each do |word|
sorted = SortedLetter.find_by_sorted(word.sorted_letters)
if sorted
SortedLetter.update(sorted.id, :anagrams => sorted.anagrams + " " + word.word, :count => sorted.count + 1)
else
SortedLetter.create(:sorted => word.sorted_letters, :anagrams => word.word, :count => 1)
end
end
class SortedLetter < ActiveRecord::Base
# Remember to create a migration!
end
class Word < ActiveRecord::Base
def self.anagrams(input_word)
sorted_word = input_word.split('').sort.join
anagrams = []
SortedLetter.where(sorted: sorted_word).each do |word|
anagrams = word[:anagrams].split(' ')
end
return anagrams.flatten
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment