Word Scoring - Solution and Thoughts About Optimization

August 12, 2014

I was watching a video today where they had a theoretical word scoring game. The scoring rules were as follows

I wrote this code to do the scoring:

module Scorer
  class WordScore

    def initialize
      @letters = Hash.new(0)
      @letters = @letters.merge(
                         { 'f' => 3, 'j' => 6, 
                           'x' => 12, 'a' => 2, 
                           'i' => 2, 'e' => 2, 
                           'o' => 2, 't' => 5})
    end

    def word_score(word)
      word.downcase!
      score = 0
      word.split('').each do |letter|
        score += @letters[letter]
      end
      score
    end
  end
end

counter = Scorer::WordScore.new
puts "The score is #{counter.word_score('XRay Machine')}"
puts "The score is #{counter.word_score('Jabbt')}"

My biggest gripe at the moment is this line of code:

@letters = Hash.new(0)
      @letters = @letters.merge(
                         { 'f' => 3, 'j' => 6, 
                           'x' => 12, 'a' => 2, 
                           'i' => 2, 'e' => 2, 
                           'o' => 2, 't' => 5})

There must be a simpler and better way to do this. I am going to dig into the different Ruby collections over the next few days to fix that line of code. Thereafter I would like to jump into the loop I do in these lines:

word.split('').each do |letter|
  score += @letters[letter]
end

Again there must be a more Ruby way of doing this kind of thing, not only that but there must be a more efficient way of calculating the score.

As an aside I didn’t get a chance to write more code in converting DbScriptomate to Ruby so that is left for tomorrow.


Discussion, links, and tweets

My name is Deon Heyns and I am a developer learning things and documenting them in realtime. Python, Ruby, Scala, .NET, and Groovy are all languages I have written code in. I appeared in the New York Post once. I host my code up at GitHub and Bitbucket so have a look at my code, fork it and send those pull requests.

comments powered by Disqus