Skip to content

Instantly share code, notes, and snippets.

@ygrenzinger
Created August 7, 2019 20:32
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 ygrenzinger/9bfeb914d5943c78e5adb1255b2ccad4 to your computer and use it in GitHub Desktop.
Save ygrenzinger/9bfeb914d5943c78e5adb1255b2ccad4 to your computer and use it in GitHub Desktop.
Bowling Kata in Dart
import 'package:cli/cli.dart';
import 'package:test/test.dart';
// https://learnxinyminutes.com/docs/dart/
// http://codingdojo.org/kata/Bowling/
int parseRoll(String roll) {
if (roll == 'X') {
return 10;
}
if (roll == '-') {
return 0;
}
return int.parse(roll);
}
bool isStrike(rollScore) {
return rollScore == 'X';
}
bool isSpare(rollScore) {
return rollScore == '/';
}
int computeStrikeScore(List<String> frames, index) {
var firstBonusRoll = frames[index + 1][0];
var secondBonusRoll =
isStrike(firstBonusRoll) ? frames[index + 2][0] : frames[index + 1][1];
return 10 + parseRoll(firstBonusRoll) + parseRoll(secondBonusRoll);
}
int computeFrameScore(List<String> frames, index) {
var firstRoll = frames[index][0];
if (isStrike(firstRoll)) {
return computeStrikeScore(frames, index);
}
if (isSpare(frames[index][1])) {
return 10 + parseRoll(frames[index + 1][0]);
}
var secondRoll = frames[index][1];
return parseRoll(firstRoll) + parseRoll(secondRoll);
}
int score(String rolls) {
var frames = rolls.split(' ');
var sum = 0;
var index = 0;
while (index < 10) {
sum += computeFrameScore(frames, index);
index++;
}
return sum;
}
// https://codeburst.io/top-X-array-utility-methods-you-should-know-dart-feb2648ee3a2
void main() {
test("bowling score when only failed rolls", () {
var rolls = '-- -- -- -- -- -- -- -- -- --';
expect(score(rolls), equals(0));
});
test("bowling score when 9 pin is down at each frame (aka turn)", () {
var rolls = '9- 9- 9- 9- 9- 9- 9- 9- 9- 9-';
expect(score(rolls), equals(90));
});
test('bowling score when 1 pin is down at each roll', () {
var rolls = '11 11 11 11 11 11 11 11 11 11';
expect(score(rolls), equals(20));
});
test('bowling score when 1 spare', () {
var rolls = '8/ 2- -- -- -- -- -- -- -- --';
expect(score(rolls), equals(14));
});
test('bowling score when 1 strike', () {
var rolls = 'X 32 -- -- -- -- -- -- -- --';
expect(score(rolls), equals(20));
});
test('bowling score when only strikes', () {
var rolls = 'X X X X X X X X X X X X';
expect(score(rolls), equals(300));
});
test('', () {
var rolls = '5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5/ 5';
expect(score(rolls), equals(150));
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment