Problem of the Day
A new programming or logic puzzle every Mon-Fri

Child's Play

Welcome back to another awesome week! Today's problem comes to us from @monkbroc

My son has a toy that speaks English words. It has 3 slots for plastic letters. When the slots are full and the letters make up a real word, the toy will read it. The toy comes with 2 of the following letters: D E G M O P, and 1 of each other. So it's possible to spell MOM but not BOB.

Write a program to list all 3 letter words in the English language that can be spelled on that toy.

Most Linux distros come with a built in dictionary or you can find one by searching the internet. Here is one I found for English.

Permalink: http://problemotd.com/problem/childs-play/

Comments:

  • Anonymous - 10 years, 4 months ago

    My solution in Ruby. ruby words.rb

    # words.rb
    class WordMatcher
      def self.match_all_from_dictionary_file(dictionary, letters, word_length)
        word_matcher = WordMatcher.new letters, word_length
        File.open(dictionary).each do |line|
          word = line.chomp
          puts word if word_matcher.matches?(word)
        end
      end
    
      attr_reader :letters, :word_length, :available_letters
    
      def initialize(letters, word_length)
        @letters = letters
        @word_length = word_length
    
        @available_letters = parse_word_to_letters(letters)
      end
    
      def matches?(word)
        word.length == word_length && matches_letters?(word)
      end
    
      def matches_letters?(word)
        word_letters = parse_word_to_letters(word)
        word_letters.all? { |letter, count| enough_letters(letter, count) }
      end
    
      def enough_letters(letter, count)
        (available_letters[letter] || 0) >= count
      end
    
      def parse_word_to_letters(word)
        word_letters = {}
        word.each_char do |letter|
          letter.downcase!
          word_letters[letter] = (word_letters[letter] || 0) + 1
        end
        word_letters
      end
    end
    
    if __FILE__ == $0
      dictionary = (ARGV[0] || "wordlist.txt")
      letters = (ARGV[1] || "abcddeefgghijklmmnooppqrstuvwxyz")
      word_length = (ARGV[2] || '3').to_i
    
      WordMatcher.match_all_from_dictionary_file(dictionary, letters, word_length)
    
    end
    

    reply permalink

Content curated by @MaxBurstein