Skip to content

Instantly share code, notes, and snippets.

@haru01
Created May 16, 2012 21:51
Show Gist options
  • Save haru01/2714258 to your computer and use it in GitHub Desktop.
Save haru01/2714258 to your computer and use it in GitHub Desktop.
bowling
# encoding: utf-8
class BowlingGame
attr_reader :rolls
def initialize(rolls)
@rolls = rolls
end
def score
(1..10).map { |frame_number|
rolls[range(frame_number)]
}.flatten.reduce(:+)
end
def range(frame_number)
first_i = (frame_number - 1) * 2
second_i = first_i + 1
return (first_i..second_i + 3) if frame_number <= 8 and double_strike?(first_i)
return (first_i..second_i + 2) if strike?(first_i)
return (first_i..second_i + 1) if spare?(first_i)
(first_i..second_i)
end
def spare?(first_i)
(rolls[first_i] + rolls[first_i + 1]) == 10 and !strike?(first_i)
end
def strike?(first_i)
rolls[first_i] == 10
end
def double_strike?(first_i)
strike?(first_i) and strike?(first_i + 2)
end
end
describe "ボウリングのスコア" do
subject { BowlingGame.new(rolls).score }
context "すべてガーターの場合のボーリング計算が出来ること" do
let(:rolls) { [0] * 21 }
it { should == 0 }
end
context "ボーナスなしのスコア計算ができること" do
let(:rolls) { ([1] * 20).concat([0]) }
it { should == 20 }
end
context "初回スペアの場合のスコア計算ができること" do
let(:rolls) { [5, 5, 3].concat([0] * 18) }
it { should == (5 + 5 + 3) + 3 }
end
context "途中スペアの場合のスコア計算ができること" do
let(:rolls) { ([0] * 16).concat([5, 5, 3, 4, 0]) }
it { should == (5 + 5 + 3) + 3 + 4 }
end
context "最後スペアの場合のスコア計算ができること" do
let(:rolls) { ([0] * 18).concat([5, 5, 3]) }
it { should == (5 + 5 + 3) }
end
context "初回ストライクの場合のスコア計算ができること" do
let(:rolls) { [10, 0, 3, 4].concat([0] * 17) }
it { should == (10 + 0 + 3 + 4) + 3 + 4 }
end
context "途中ストライクの場合のスコア計算ができること" do
let(:rolls) { ([0] * 16).concat([10, 0, 7, 5, 0]) }
it { should == (10 + 0 + 7 + 5) + 7 + 5 }
end
context "ラストフレームの連続ストライク場合のスコア計算ができること" do
let(:rolls) { ([0] * 18).concat([10, 10, 10]) }
it { should == (10 + 10 + 10) }
end
context "9フレームからの連続ストライク場合のスコア計算ができること《注意》" do
let(:rolls) { ([0] * 16).concat([10, 0, 10, 1, 7]) }
it { should == (10 + 10 + 1) + 10 + 1 + 7 }
end
context "ダブルの場合のスコアが計算できること" do
let(:rolls) { [10, 0, 10, 0, 5, 4].concat([0] * 15) }
it { should == (10 + 10 + 5) + (10 + 5 + 4) + 5 + 4 }
end
context "トリプルの場合のスコア計算ができること" do
let(:rolls) { [10, 0, 10, 0, 10, 0, 4, 5].concat([0] * 15) }
it { should == (10 + 10 + 10) + (10 + 10 + 4) + (10 + 4 + 5) + 4 + 5 }
end
context "パーフェクトの場合のスコア計算ができること" do
let(:rolls) { ([10, 0] * 9).concat([10, 10, 10]) }
it { should == 300 }
end
context "サンプルの計算が出来ること" do
let(:rolls) { [5,4,0,0,10,0,9,1,6,3,7,0,6,2,10,0,10,0,1,9,5] }
it { should == 125 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment