Skip to content

Instantly share code, notes, and snippets.

@dan5
Created Apr 9, 2011
Embed
What would you like to do?
def strike?(pins, idx)
pins[idx * 2] == 10
end
def spare?(pins, idx)
pins[idx * 2] + pins[idx * 2 + 1] == 10
end
def score_strike_spare(pins)
score = 0
games = [(pins.size + 1) / 2 - 1, 9].min
games.times do |i|
next_idx = (i + 1) * 2
if strike?(pins, i)
score += pins[next_idx]
score += pins[next_idx + 1].to_i > 0 ? pins[next_idx + 1] : pins[next_idx + 2].to_i
elsif spare?(pins, i)
score += pins[next_idx]
end
end
score
end
def score(pins)
pins.inject(&:+) + score_strike_spare(pins)
end
def bowl(n)
@pins ||= []
@pins << n
score(@pins)
end
pins = [1, 4, 2, 8, 5, 0, 10, 0, 0, 4, 5, 5, 2, 0, 6, 1, 10, 0, 10, 5, 5]
pins.each do |n|
puts sprintf("%2d %d\n", n, bowl(n))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment