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!
Hey. Thanks for your solutions. Interesting approach! :)
ReplyDeleteHi Martha, thanks for passing by
ReplyDelete