I used to love watching Countdown (https://en.wikipedia.org/wiki/Countdown_(game_show)) on TV after school each day, and I used to be super jealous at how clever the contestants were to be able to quickly unscramble the anagrams and form words from the randomly selected consonants and vowels (yes, my path to nerdom started at a young age).
So, just for fun I decided to write a little Ruby script that would allow me to solve the Countdown word games in double-quick time. There is really nothing to this little script, but let me talk through the logic. It creates a ‘dictionary’ of words by loading in a text file, containing a list of English words on each line, and then re-orders the letters of each word in alphabetical order. The ordered and un-ordered letter sequences are added to a Hash as keys and values, which serves as a look up against user-entered letter sequences. Any letter sequences which match, the original word is added to the result set.
Take a look at the code below, and leave a comment if there is a better way to do this!
# Method declarations
def dictionary (wordlist)
ordered_word_list = Hash.new
wordlist.each do |w|
ordered_word_list[w.chomp.chars.sort.join.to_s] = w.chomp.to_s
end
return ordered_word_list
end
def match_words (user_input, d)
#order the input string for comparison against ordered_word_list keys
ordered_input = user_input.chars.sort.join.to_s
#matching loop, where there is a hit - add the value for the key to the result set
result_set = []
d.each do |k, v|
if (k.length > 3) && (ordered_input.include? k)
result_set << v
end
end
puts "Matches identified:"
puts result_set
end
def display_message
puts "This appication takes a string of letters from the standard input, and returns a list of words which can be formed from those letters..."
puts "Like Countdown..."
puts "Please enter the string to match:"
STDOUT.flush
end
# entry point for main program
# create the ordered_word_list from a word list file
puts "Generating dictionary..."
d = dictionary (File.open('words.txt'))
puts "Dictionary successfully created!"
#get user input to match against
display_message
user_input = gets.chomp.downcase
# pass this input to match_words to generate the hits
match_words user_input, d