Skip to content

Instantly share code, notes, and snippets.

@Dispader
Last active August 3, 2016 17:26
Show Gist options
  • Save Dispader/5ae1e102ae2a8dbd2e8e to your computer and use it in GitHub Desktop.
Save Dispader/5ae1e102ae2a8dbd2e8e to your computer and use it in GitHub Desktop.
one proposed solution to the greed.rb problem, proposed in [Ian Whitney's Ruby Brown Bag](https://github.com/IanWhitney/ruby_brownbag}, for comment — please, please comment: I'm a Ruby tyro, and could use the help. (And many thanks to Ian for his great session, and Chris Crosby-Schmidt for inspiring the approach!)
class Greed
def self.score(dice)
# initialize a score
score = 0
# create a hash of the roll (face values) and the number of times rolled
rolls = dice.inject(Hash.new(0)) {|hash, roll| hash[roll] += 1; hash }
# for each set of 1s, add 1000 points to the score
if rolls[1]/3 > 0
score += ( rolls[1]/3 ) * 1000 # award 1000 points per set of 1s
rolls[1] -= ( rolls[1]/3 ) * 3 # remove each set from the roll count
end
# for each other set, add 100 points per set face value
(2..6).each { |roll|
if rolls[roll]/3 > 0
score += ( rolls[roll]/3 ) * ( 100 * roll) # award 100 * roll per set
rolls[roll] -= ( rolls[roll]/3 ) * 3 # remove sets from count
end
}
# TODO: FIX dry violation for above two methods
# for each (single) roll that has a pont value, award points to the score
{ 1 => 100, 5 => 50 }.each { |roll, points_per_roll|
score += points_per_roll * rolls[roll]
}
# yield the score
score
end
end
@enebo
Copy link

enebo commented Aug 3, 2016

@Dispader ... nor me :) I have not checked exercism but I have a tab open and will check it out.

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