Created
September 8, 2016 12:13
-
-
Save rofr/48b99210dc2db15200bca5333786d73d to your computer and use it in GitHub Desktop.
This file contains 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
package kata.bowling; | |
import static org.junit.Assert.*; | |
import org.junit.Before; | |
import org.junit.Test; | |
public class BowlingTests { | |
Series series; | |
@Before | |
public void setUp() { | |
series = new Series(); | |
} | |
@Test | |
public void testAllGutters() { | |
for(int i=0;i<20;i++) series.roll(0); | |
assertEquals(0, series.score()); | |
} | |
@Test | |
public void testAllStrikes() { | |
for(int i=0;i<12;i++) series.roll(10); | |
assertEquals(300, series.score()); | |
} | |
@Test | |
public void testAllOnes() { | |
for(int i=0; i< 20; i++) { | |
series.roll(1); | |
} | |
assertEquals(20, series.score()); | |
} | |
} |
This file contains 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
package kata.bowling; | |
public class Series { | |
int[] rolls = new int[21]; | |
int currentRoll = 0; | |
public void roll(int pins) { | |
rolls[currentRoll++] = pins; | |
if (pins == 10 && currentRoll < 19) currentRoll++; | |
} | |
public int score() { | |
int result = 0; | |
for(int i=0;i<20;i+=2) { | |
if (isStrike(i)) { | |
result += 10; | |
result += strikeBonus(i); | |
} | |
else if (isSpare(i)) { | |
result += 10; | |
result += rolls[i+2]; | |
} | |
else result += rolls[i] + rolls[i+1]; | |
} | |
return result; | |
} | |
private int strikeBonus(int rollIndex) { | |
if (lastFrame(rollIndex)) return rolls[rollIndex+1] + rolls[rollIndex+2]; | |
else if (nextToLastFrame(rollIndex)) return rolls[rollIndex+2] + rolls[rollIndex+3]; | |
int result = rolls[rollIndex+2]; | |
if (isStrike(rollIndex+2)) result += rolls[rollIndex+4]; | |
else result += rolls[rollIndex+3]; | |
return result; | |
} | |
private boolean lastFrame(int rollIndex) { | |
return rollIndex == 18; | |
} | |
private boolean nextToLastFrame(int rollIndex) { | |
return rollIndex == 16; | |
} | |
private boolean isSpare(int rollIndex) { | |
return ! isStrike(rollIndex) && rolls[rollIndex] + rolls[rollIndex+1] == 10; | |
} | |
private boolean isStrike(int rollIndex) { | |
return rolls[rollIndex] == 10; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment