forked from tpapendieck/ciip-examples
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
37 lines
1.2 KiB
37 lines
1.2 KiB
package de.edu.hsfulda.ciip.tdd;
|
|
|
|
import java.util.regex.Matcher;
|
|
import java.util.regex.Pattern;
|
|
|
|
public class BownlingCalculator {
|
|
private static final int PINS_IN_FRAME = 10;
|
|
private static final String SPARE = "(\\d)/ (\\d)";
|
|
private static final String INCOMPLETE_FRAME = "\\d";
|
|
|
|
@FunctionalInterface
|
|
private interface FrameCalculator {
|
|
int evaluate(Matcher frameStructure);
|
|
}
|
|
|
|
private static final int SPARE_FRAME_FOLLOWING_THROW = 2;
|
|
private static final int SPARE_FRAME_FIRST_THROW = 1;
|
|
|
|
public int evaluate(String listOfThrows) {
|
|
int sum = 0;
|
|
sum += evaluateFrames(listOfThrows, INCOMPLETE_FRAME, m -> Integer.parseInt(m.group()));
|
|
sum += evaluateFrames(listOfThrows, SPARE, m -> PINS_IN_FRAME//
|
|
- Integer.parseInt(m.group(SPARE_FRAME_FIRST_THROW))
|
|
+ Integer.parseInt(m.group(SPARE_FRAME_FOLLOWING_THROW)));
|
|
return sum;
|
|
}
|
|
|
|
private int evaluateFrames(String listOfThrows, String frameStructurePattern, FrameCalculator frameCalculator) {
|
|
Matcher singleDigit = Pattern.compile(frameStructurePattern).matcher(listOfThrows);
|
|
int frameValue = 0;
|
|
while (singleDigit.find()) {
|
|
frameValue += frameCalculator.evaluate(singleDigit);
|
|
}
|
|
return frameValue;
|
|
}
|
|
|
|
}
|