Wednesday, 4 April 2012

Ruby Koan #183 about scoring project: The Greed Game

When I searched the site for koan greed I was not surprised to see 19 answers and though I've seen very performing implementations, I was quite surprised to see that nobody solved the problem with a class(maybe because about_classes was the next set of koans?), which was my first take. I admit I got lost in refactoring before looking for a comparison, but this is just my spare time.
Here it goes!
class Greed
  def initialize(dice_faces)
    @dice_count = count_occurrences_in(dice_faces)
    @score      = calculate_score!
  end

  attr_reader :score

  def calculate_score!
    @score  = 0
    @score += score_of_triple_1(1000)
    @score += score_of_other_triples(100)
    @score += score_of_5s(50)
    @score += score_of_1s(100)
  end

private

  def score_of_5s(score)
    face_score(5, score)
  end

  def score_of_1s(score)
    face_score(1, score)
  end

  def score_of_other_triples(score_each)
    score_triples score_each, (2..6).to_a
  end

  # >>>>> here starts the meat

  def score_of_triple_1(score)
    score if @dice_count[1] >= 3
  end

  def score_triples(score, faces)
    partial_score = 0
    @dice_count.each_with_index do |times, face|
      next unless faces.include? face
      partial_score += score * face if times >= 3
    end
    partial_score
  end

  # faces counted in triples are escluded
  def face_score(face, score = 0)
    times = @dice_count[face]
    score * (times % 3)
  end

  # <<<<< here ends the meat

  def count_occurrences_in(dice_faces)
    # nil for 0 which is not a face, then the 6 faces
    [nil,0,0,0,0,0,0].tap do |occurrences|
      dice_faces.each { |face| occurrences[face] += 1 }
    end
  end

end


def score(dice)
  # You need to write this method
  Greed.new(dice).score
end


Even considering only "the meat" of my class, the solution on github is still a few lines shorter... Hei, wait, I could implement the sandwitch in score_triple and count_times! I feel like Randy Marshall watching cooking programs!

2 comments:

  1. Hey. Thanks for your solutions. Interesting approach! :)

    ReplyDelete
  2. Hi Martha, thanks for passing by

    ReplyDelete