Skip to content

Instantly share code, notes, and snippets.

@jacegu
Created January 4, 2011 18:47
Show Gist options
  • Save jacegu/765192 to your computer and use it in GitHub Desktop.
Save jacegu/765192 to your computer and use it in GitHub Desktop.
My implementation of greed dice game for Ruby Koans
class Roll
FIFTY_POINTS = 50
HUNDRED_POINTS = 100
THOUSAND_POINTS = 1000
def initialize(rolls)
@ocurrences = ocurrences_of_each_number(rolls)
end
def score
a_1000_points_for_each_set_of_3_1s +
a_100_points_for_each_1_not_part_of_a_set_of_3 +
a_50_points_for_each_5_not_part_of_a_set_of_3 +
a_100_times_the_number_for_each_group_of_3_numbers_other_than_1
end
private
def ocurrences_of_each_number(rolls)
ocurrences = Hash.new
(1..6).each{ |number| ocurrences[number] = rolls.count(number) }
ocurrences
end
def a_1000_points_for_each_set_of_3_1s
(@ocurrences[1] / 3) * THOUSAND_POINTS
end
def a_100_points_for_each_1_not_part_of_a_set_of_3
(@ocurrences[1] % 3) * HUNDRED_POINTS
end
def a_50_points_for_each_5_not_part_of_a_set_of_3
(@ocurrences[5] % 3) * FIFTY_POINTS
end
def a_100_times_the_number_for_each_group_of_3_numbers_other_than_1
ocurrences_of_others_than_1 = @ocurrences.select{|number| number != 1}
score = 0
ocurrences_of_others_than_1.each do |number, times|
score += number * HUNDRED_POINTS * (times / 3)
end
score
end
end
def score(dice)
Roll.new(dice).score
end
@alberto
Copy link

alberto commented Jan 4, 2011

Muy elegante!
Sólo un pequeño pero, en el caso de un triple 5 debería sumar 500, y tu código suma 650, si no me equivoco.
Por otra parte, son sólo 5 dados, así que se podría simplificar un poquito más el código ;)

@jacegu
Copy link
Author

jacegu commented Jan 4, 2011

:-S Me habías asustado! Había probado a que que pasaba los tests de las Koans y no había encontrado errores, pero me has hecho dudar. Da 500 :·D

@alberto
Copy link

alberto commented Jan 4, 2011

cierto, jeje, no me hagas ni caso xD

@jjballano
Copy link

No me gustan las constantes con nombre igual al número, no quitamos los números mágicos, los camuflamos. Decir CIEN = 100 y luego usar CIEN es exactamente lo mismo que usar un 100.

@jacegu
Copy link
Author

jacegu commented Jan 4, 2011

Toda la razón del mundo. Debería haber usado cual es el concepto para esas puntuaciones en vez de el número. Algo como POINTS_FOR_3_ONES, etc...

@jjballano
Copy link

Pero ten cuidado, que como me dijeron a mi, el 100 no son los puntos para los que son distintos de 1 y 5, sino que es el multiplicador! lo digo de cara al nombre

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment