Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created October 27, 2008 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcoglan/20087 to your computer and use it in GitHub Desktop.
Save jcoglan/20087 to your computer and use it in GitHub Desktop.
data = ARGV.dup
name, scores = data.shift, data.map { |n| n.to_i }
# Group scores into frames
frames = scores.inject([]) do |table, score|
previous = table.last
frame = previous || [0]
frame = [0] if frame.size == 3 or frame[1] == 10
table << frame unless frame == previous
frame << score
table
end
# Calculate bonuses and total
total = 0
frames.each_with_index do |frame, i|
f, g, x, y = frames[i+1], frames[i+2], *frame[1..2]
frame[0] = f[1] if y and x + y == 10
frame[0] = f[1] + (f[2] || g[1]) if x == 10
total += frame.inject(0) { |a,b| a + b } if i < 10
frame[3] = total
end
# Print table
puts "#{ name }'s final score: #{ total }\n\n"
puts "Frame\t\tRoll\t\tRoll\t\tScore"
frames.each_with_index do |frame, i|
x, y, s = frame[1..3]
first = (x == 10) ? 'X' : x
second = y && (y == 0 ? '-' : (x + y == 10 ? '/' : y))
puts "#{i < 10 ? i+1 : '*'}\t\t#{first}\t\t#{second}\t\t#{s if i < 10}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment