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.

40 lines
1.3 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. sum += evaluateFrames(listOfThrows, "X (\\d)(\\d)", m -> PINS_IN_FRAME//
  21. + Integer.parseInt(m.group(1))
  22. + Integer.parseInt(m.group(2)));
  23. return sum;
  24. }
  25. private int evaluateFrames(String listOfThrows, String frameStructurePattern, FrameCalculator frameCalculator) {
  26. Matcher singleDigit = Pattern.compile(frameStructurePattern).matcher(listOfThrows);
  27. int frameValue = 0;
  28. while (singleDigit.find()) {
  29. frameValue += frameCalculator.evaluate(singleDigit);
  30. }
  31. return frameValue;
  32. }
  33. }