Created
September 20, 2011 19:32
-
-
Save albert-chang0/1230093 to your computer and use it in GitHub Desktop.
Average bowling score
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
213025x141570447043- | |
5/630/038/3427725370- | |
44x07109/x2071016/2 | |
448/418/0270808/818/1 | |
612144x43x6/250/81- | |
308/039/908/3/318031- | |
09165026701716146/54- | |
3/400017314217617/1/0 | |
x7/529060204/8072x1/ | |
71705/9013107161126/x |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# | |
# scoring: | |
# * [0-9]{2} - open frame, add points | |
# * [0-9]/ - spare, count next ball's score | |
# * x - strike, count next two balls' scores | |
# * - - no third ball on 10th frame | |
# | |
# find the average of all the games, rounded to the nearest hundredth | |
gameslist = "sample.txt" | |
# pattern to split line (representing a game) into frames | |
pattern = /[0-9\/x]{1,2}$|[0-9]{2}|[0-9]\/|x/ | |
score = 0 # running score | |
game_count = 0 # game counter | |
File.open(gameslist, "r") do |file| | |
while line = file.gets | |
current = 0 | |
# each line is a game | |
game_count += 1 | |
line.scan(pattern).each_with_index do |frame, i| | |
# no such thing as 11th frame, only 10th frame bonus | |
next if i == 10 | |
# spare, add 10 and next ball's points as bonus | |
score += if frame[1] == "/" | |
# next ball is a strike, add 10 | |
10 + if line[current + 2] == "x" | |
10 | |
# next ball wasn't a strike, add next ball's points | |
else | |
line[current + 2].to_i | |
end | |
# strike, add 10 and next 2 balls' points as bonuses | |
elsif frame[0] == "x" | |
# next frame is strike | |
10 + if line[current + 1] == "x" | |
# turkey | |
10 + if line[current + 2] == "x" | |
10 | |
# not a strike, add the points | |
else | |
line[current + 2].to_i | |
end | |
# next frame is spare, just add 10 | |
elsif line[current + 2] == "/" | |
10 | |
# next frame is open, add those two balls' points | |
else | |
line[current + 1].to_i + line[current + 2].to_i | |
end | |
# open frame, just add the points | |
else | |
frame[0].to_i + frame[1].to_i | |
end | |
current += frame.size | |
end | |
end | |
end | |
puts "Average: #{((score / game_count.to_f) * 100).round / 100.0}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment