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.

29 lines
1.1 KiB

import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BowlingGameCalculator {
private static final Pattern SINGLE_VALUE_PATTERN = Pattern.compile("\\d");
private static final Pattern SPARE_PATTERN = Pattern.compile("(\\d)[ ,]*/[ -,]*(\\d)");
private static final int INITIAL_SCORE_VALUE = 0;
public int score(String playerResult) {
int playerScore = INITIAL_SCORE_VALUE;
playerScore += scoreMatch(SINGLE_VALUE_PATTERN.matcher(playerResult), (spareMatcher) -> Integer.parseInt(spareMatcher.group()));
playerScore += scoreMatch(SPARE_PATTERN.matcher(playerResult), (spareMatcher) ->
10 + Integer.parseInt(spareMatcher.group(2))
- Integer.parseInt(spareMatcher.group(1)));
return playerScore;
}
private int scoreMatch(Matcher scoreMatch, Function<Matcher, Integer> scorer) {
int playerScore = INITIAL_SCORE_VALUE;
while (scoreMatch.find()) {
playerScore += scorer.apply(scoreMatch);
}
return playerScore;
}
}