Solving ‘Countdown’ with Ruby

I used to love watching Countdown ( 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 =

        wordlist.each do |w|

                            ordered_word_list[w.chomp.chars.sort.join.to_s] = w.chomp.to_s      


        return ordered_word_list


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



    puts "Matches identified:"

    puts result_set


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:"



# entry point for main program

# create the ordered_word_list from a word list file

puts "Generating dictionary..."

d = dictionary ('words.txt'))

puts "Dictionary successfully created!"

#get user input to match against


user_input = gets.chomp.downcase

# pass this input to match_words to generate the hits

match_words user_input, d

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s