lots of exercises in java... from https://github.com/exercism/java

OpticalCharacterReader.java 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /*
  4. * This example solution uses the abbreviation "SSD", short for Seven-Segment Display, throughout.
  5. *
  6. * For more information, see https://en.wikipedia.org/wiki/Seven-segment_display.
  7. */
  8. final class OpticalCharacterReader {
  9. private static final int ROWS_PER_LINE = 4;
  10. private static final int COLS_PER_SSD = 3;
  11. String parse(final List<String> input) {
  12. validateInput(input);
  13. final List<String> parsedLines = new ArrayList<>();
  14. for (int nLine = 0; nLine < input.size() / ROWS_PER_LINE; nLine++) {
  15. final int nFirstRowCurrentLine = nLine * ROWS_PER_LINE;
  16. final int nFirstRowNextLine = nFirstRowCurrentLine + ROWS_PER_LINE;
  17. final List<String> currentLine = input.subList(nFirstRowCurrentLine, nFirstRowNextLine);
  18. parsedLines.add(parseLine(currentLine));
  19. }
  20. return String.join(",", parsedLines);
  21. }
  22. private String parseLine(final List<String> currentLine) {
  23. final List<String> parsedDigits = new ArrayList<>();
  24. for (int nSsd = 0; nSsd < currentLine.get(0).length() / COLS_PER_SSD; nSsd++) {
  25. final int nFirstColCurrentSsd = nSsd * COLS_PER_SSD;
  26. final int nFirstColNextSsd = nFirstColCurrentSsd + COLS_PER_SSD;
  27. final List<String> currentSsdConfiguration = new ArrayList<>();
  28. // Bottom row of each line is a spacer, so we ignore that row when constructing SSD configurations.
  29. for (int nRow = 0; nRow < ROWS_PER_LINE - 1; nRow++) {
  30. currentSsdConfiguration.add(currentLine.get(nRow).substring(nFirstColCurrentSsd, nFirstColNextSsd));
  31. }
  32. parsedDigits.add(Digit.fromSsdConfiguration(currentSsdConfiguration));
  33. }
  34. return String.join("", parsedDigits);
  35. }
  36. private void validateInput(final List<String> input) {
  37. final int inputRowCount = input.size();
  38. if (inputRowCount == 0 || inputRowCount % 4 != 0) {
  39. throw new IllegalArgumentException(
  40. "Number of input rows must be a positive multiple of " + ROWS_PER_LINE);
  41. }
  42. final int inputColCount = input.get(0).length();
  43. if (inputColCount == 0 || inputColCount % 3 != 0) {
  44. throw new IllegalArgumentException(
  45. "Number of input columns must be a positive multiple of " + COLS_PER_SSD);
  46. }
  47. }
  48. }