Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Last active December 23, 2015 12:59
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 seanhandley/48d4e42c90b533f6d966 to your computer and use it in GitHub Desktop.
Save seanhandley/48d4e42c90b533f6d966 to your computer and use it in GitHub Desktop.
A script to find the words in the dictionary that have the most anagrams
# anagrams.rb
#
# A script to find the words in the dictionary that have the most anagrams.
require "curses"
include Curses
MAX_LENGTH = ARGV[0]
WORDS = File.readlines('/usr/share/dict/words').select{|w| w.length < MAX_LENGTH.to_i }.map(&:downcase)
WORDS_HASH = Hash[WORDS.map{|w| [w.strip,w.strip]}]
class Result
include Comparable
attr_reader :original_word, :valid_anagrams, :size
def initialize(original_word, valid_anagrams)
@original_word = original_word
@valid_anagrams = valid_anagrams
end
def <=> other
self.size <=> other.size
end
def size
valid_anagrams.count
end
end
def show_message(message)
width = message.length + 6
win = Window.new(5, width,
2,0)
win.box(?|, ?-)
win.setpos(2, 3)
win.addstr(message)
win.refresh
win.close
end
def find_words
results = []
words_with_anagrams = []
n = 0
for word in WORDS
show_message("Searched #{n}/#{WORDS.count} words...")
word.strip!
word.downcase!
permutations = word.chars.to_a.permutation(word.length).map(&:join)
valid_anagrams = []
permutations.each do |perm|
if (perm != word && !valid_anagrams.include?(perm) && WORDS_HASH[perm]) && !words_with_anagrams.include?(perm)
valid_anagrams << perm
words_with_anagrams << perm
end
end
if valid_anagrams.count > 0
results << Result.new(word, valid_anagrams)
end
n += 1
end
results
end
unless MAX_LENGTH
puts "Usage: anagrams.rb X (where X is an integer denoting maximum size of word)"
exit
end
init_screen
results = []
begin
crmode
setpos(0,0)
addstr("There are #{WORDS.count} words in the dictionary that are shorter than #{MAX_LENGTH} characters... Hit any key to start")
refresh
getch
results = find_words
refresh
ensure
close_screen
end
results.sort.reverse.take(30).each do |result|
puts "#{result.original_word} has #{result.size} anagrams: #{result.valid_anagrams.join(', ')}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment