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

  1. package de.edu.hsfulda.ciip.tdd;
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4. public class BownlingCalculator {
  5. private static final int PINS_IN_FRAME = 10;
  6. private static final String SPARE = "(\\d)/ (\\d)";
  7. private static final String INCOMPLETE_FRAME = "\\d";
  8. @FunctionalInterface
  9. private interface FrameCalculator {
  10. int evaluate(Matcher frameStructure);
  11. }
  12. private static final int SPARE_FRAME_FOLLOWING_THROW = 2;
  13. private static final int SPARE_FRAME_FIRST_THROW = 1;
  14. public int evaluate(String listOfThrows) {
  15. int sum = 0;
  16. sum += evaluateFrames(listOfThrows, INCOMPLETE_FRAME, m -> Integer.parseInt(m.group()));
  17. sum += evaluateFrames(listOfThrows, SPARE, m -> PINS_IN_FRAME//
  18. - Integer.parseInt(m.group(SPARE_FRAME_FIRST_THROW))
  19. + Integer.parseInt(m.group(SPARE_FRAME_FOLLOWING_THROW)));
  20. return sum;
  21. }
  22. private int evaluateFrames(String listOfThrows, String frameStructurePattern, FrameCalculator frameCalculator) {
  23. Matcher singleDigit = Pattern.compile(frameStructurePattern).matcher(listOfThrows);
  24. int frameValue = 0;
  25. while (singleDigit.find()) {
  26. frameValue += frameCalculator.evaluate(singleDigit);
  27. }
  28. return frameValue;
  29. }
  30. }