SPOILER/CHEAT: Quick C++ solution

Jacob Fugal lukfugl at gmail.com
Fri Mar 10 17:09:45 MST 2006


In ruby. Two versions; first a "script style" one, then the
"refactored" object oriented approach. For something this simple, I'd
probably use the script style myself, but I "refactored" it for flavor
(and you never know when a toy will grow... :).

### Script style:

dictionary = {}
File.open('/usr/share/dict/words') do |file|
  file.each_line do |word|
    dictionary[word.chomp] = true
  end
end

tabulator = Hash.new(0)
File.open(ARGV[0]) do |file|
  file.each_line do |line|
    line.chomp.split(/\s/).each do |word|
      tabulator[word] += 1 if dictionary.has_key?(word)
    end
  end
end

tabulator.each{ |word,count| puts "#{word} #{count}" }

### OOP style

class Dictionary
  def initialize(filename=nil)
    @words = {}
    load_file(filename) if filename
  end

  def load_file(filename)
    File.open(filename) do |file|
      file.each_line do |word|
        @words[word.chomp] = true
      end
    end
  end

  def includes?(word)
    @words.has_key?(word)
  end
end

class Tabulator
  def initialize(filename=nil, dictionary=nil)
    @dictionary = dictionary
    @words = Hash.new(0)
    load_file(filename) if filename
  end

  def load_file(filename)
    File.open(filename) do |file|
      file.each_line do |line|
        words = words_in_line(line)
        record(*words)
      end
    end
  end

  def record(*words)
    words.each do |word|
      next if @dictionary and not @dictionary.includes?(word)
      @words[word] += 1
    end
  end

  def words
    @words.keys.sort
  end

  def each_word(&block)
    words.each &block
  end

  def count(word)
    @words[word]
  end

  def report
    each_word{ |word| puts "#{word} #{count(word)}" }
  end

  protected
  def words_in_line(line)
    line.chomp.split(/\s/)
  end
end

dictionary_file = '/usr/share/dict/words'
word_file = ARGV[0]

dictionary = Dictionary.new(dictionary_file)
tabulator = Tabulator.new(word_file, dictionary)
tabulator.report

### Jacob Fugal



More information about the PLUG mailing list