Skip to content

Instantly share code, notes, and snippets.

@crevier
Created December 15, 2017 22:25
Show Gist options
  • Save crevier/58b8750a8b566d21eb63de29186c8724 to your computer and use it in GitHub Desktop.
Save crevier/58b8750a8b566d21eb63de29186c8724 to your computer and use it in GitHub Desktop.
Bowling Kata : This snipet is the result of a pair programing session with thomas in Starbuck (avenue de l'opera Paris)
class Bowling {
static int score(def rolls) {
def score = scoreWithoutBonus(rolls)
def frames = 0..9
frames.each {
def firstRollInFrame = it * 2
if (isStrike(rolls, firstRollInFrame)) {
score += strikeBonus(rolls, firstRollInFrame)
} else if (isSpare(rolls, firstRollInFrame)) {
score += spareBonus(rolls, firstRollInFrame)
}
}
score
}
static int scoreWithoutBonus(rolls) {
rolls.subList(0, 20).sum()
}
static int bonusRollIndex(firstRollInFrame) {
firstRollInFrame + 2
}
static int strikeBonus(rolls, firstRollInFrame) {
def bonusRollIndex = bonusRollIndex(firstRollInFrame)
def step = isStrike(rolls, bonusRollIndex) ? 2 : 1
rolls[bonusRollIndex] + rolls[bonusRollIndex + step]
}
static int spareBonus(rolls, firstRollInFrame) {
def bonusRollIndex = bonusRollIndex(firstRollInFrame)
rolls[bonusRollIndex]
}
static boolean isStrike(rolls, firstRollInFrame) {
rolls[firstRollInFrame] == 10 && rolls[firstRollInFrame + 1] == 0
}
static boolean isSpare(rolls, index) {
rolls[index] + rolls[index + 1] == 10
}
}
/*
-----Tests------
*/
def allSamePins(pins) { allSamePins(pins, 20) }
def allSamePins(pins, n) { [pins] * n }
spare = [2, 8]
strike = [10, 0]
allZeros = allSamePins(0)
allOnes = allSamePins(1)
allOnesWithSpare = spare + allSamePins(1, 18)
allSparesAndFour = spare * 10 + [4]
allOnesWithTwoSpares = spare * 2 + allSamePins(1, 16)
allOnesWithStrike = strike + allSamePins(1, 18)
allStrikes = strike * 10 + [10, 10]
assert Bowling.score(allZeros) == 0
assert Bowling.score(allOnes) == 20
assert allOnesWithSpare == [2, 8] + [1] * 18
assert Bowling.score(allOnesWithSpare) == 29
assert Bowling.score(allOnesWithTwoSpares) == 39
assert Bowling.score(allSparesAndFour) == 122
assert Bowling.score(allOnesWithStrike) == 30
assert Bowling.score(allStrikes) == 300
assert Bowling.score((spare + strike) * 5 + spare) == 200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment