Avatar of ESV

ESV's solution

to OCR Numbers in the Java Track

Published at Oct 10 2019 · 0 comments
Instructions
Test suite
Solution

Given a 3 x 4 grid of pipes, underscores, and spaces, determine which number is represented, or whether it is garbled.

Step One

To begin with, convert a simple binary font to a string containing 0 or 1.

The binary font uses pipes and underscores, four rows high and three columns wide.

     _   #
    | |  # zero.
    |_|  #
         # the fourth row is always blank

Is converted to "0"

         #
      |  # one.
      |  #
         # (blank fourth row)

Is converted to "1"

If the input is the correct size, but not recognizable, your program should return '?'

If the input is the incorrect size, your program should return an error.

Step Two

Update your program to recognize multi-character binary strings, replacing garbled numbers with ?

Step Three

Update your program to recognize all numbers 0 through 9, both individually and as part of a larger string.

 _ 
 _|
|_ 
   

Is converted to "2"

      _  _     _  _  _  _  _  _  #
    | _| _||_||_ |_   ||_||_|| | # decimal numbers.
    ||_  _|  | _||_|  ||_| _||_| #
                                 # fourth line is always blank

Is converted to "1234567890"

Step Four

Update your program to handle multiple numbers, one per line. When converting several lines, join the lines with commas.

    _  _ 
  | _| _|
  ||_  _|
         
    _  _ 
|_||_ |_ 
  | _||_|
         
 _  _  _ 
  ||_||_|
  ||_| _|
         

Is converted to "123,456,789"

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Source

Inspired by the Bank OCR kata http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

OpticalCharacterReaderTest.java

import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Arrays;

import static org.junit.Assert.assertEquals;

public class OpticalCharacterReaderTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void testReaderRecognizesSingle0() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "| |",
                "|_|",
                "   "
        ));

        assertEquals("0", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle1() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "   ",
                "  |",
                "  |",
                "   "
        ));

        assertEquals("1", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderReturnsQuestionMarkForUnreadableButCorrectlySizedInput() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "   ",
                "  _",
                "  |",
                "   "
        ));

        assertEquals("?", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderThrowsExceptionWhenNumberOfInputLinesIsNotAMultipleOf4() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Number of input rows must be a positive multiple of 4");

        new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "| |",
                "   "
        ));
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderThrowsExceptionWhenNumberOfInputColumnsIsNotAMultipleOf3() {
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Number of input columns must be a positive multiple of 3");

        new OpticalCharacterReader().parse(Arrays.asList(
                "    ",
                "   |",
                "   |",
                "    "
        ));
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesBinarySequence110101100() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "       _     _        _  _ ",
                "  |  || |  || |  |  || || |",
                "  |  ||_|  ||_|  |  ||_||_|",
                "                           "
        ));

        assertEquals("110101100", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderReplacesUnreadableDigitsWithQuestionMarksWithinSequence() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "       _     _           _ ",
                "  |  || |  || |     || || |",
                "  |  | _|  ||_|  |  ||_||_|",
                "                           "
        ));

        assertEquals("11?10?1?0", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle2() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                " _|",
                "|_ ",
                "   "
        ));

        assertEquals("2", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle3() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                " _|",
                " _|",
                "   "
        ));

        assertEquals("3", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle4() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "   ",
                "|_|",
                "  |",
                "   "
        ));

        assertEquals("4", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle5() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "|_ ",
                " _|",
                "   "
        ));

        assertEquals("5", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle6() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "|_ ",
                "|_|",
                "   "
        ));

        assertEquals("6", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle7() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "  |",
                "  |",
                "   "
        ));

        assertEquals("7", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle8() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "|_|",
                "|_|",
                "   "
        ));

        assertEquals("8", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSingle9() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                " _ ",
                "|_|",
                " _|",
                "   "
        ));

        assertEquals("9", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesSequence1234567890() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "    _  _     _  _  _  _  _  _ ",
                "  | _| _||_||_ |_   ||_||_|| |",
                "  ||_  _|  | _||_|  ||_| _||_|",
                "                              "
        ));

        assertEquals("1234567890", parsedInput);
    }

    @Ignore("Remove to run test")
    @Test
    public void testReaderRecognizesAndCorrectlyFormatsMultiRowInput() {
        String parsedInput = new OpticalCharacterReader().parse(Arrays.asList(
                "    _  _ ",
                "  | _| _|",
                "  ||_  _|",
                "         ",
                "    _  _ ",
                "|_||_ |_ ",
                "  | _||_|",
                "         ",
                " _  _  _ ",
                "  ||_||_|",
                "  ||_| _|",
                "         "
        ));

        assertEquals("123,456,789", parsedInput);
    }

}

src/main/java/OpticalCharacterReader.java

import java.util.List;
import java.util.Objects;

public class OpticalCharacterReader {
    public OpticalCharacterReader() { }

    public String parse(List<String> lines) {
        Objects.requireNonNull(lines, "lines");
        if (0 != (lines.size() % 4)) {
            throw new IllegalArgumentException(
                "Number of input rows must be a positive multiple of 4");
        }

        final int firstInputLineLength = lines.get(0).length();
        for (int line = 0; line < lines.size(); line++) {
            Objects.requireNonNull(lines.get(line), "lines[line]");

            if (lines.get(line).length() != firstInputLineLength) {
                throw new IllegalArgumentException(
                    "Number of input columns must be consistent");
            }

            if (0 != (lines.get(line).length() % 3)) {
                throw new IllegalArgumentException(
                    "Number of input columns must be a positive multiple of 3");
            }
        }

        return Digit.parseLines(lines);
    }
}

src/main/java/Digit.java

import java.util.List;

public class Digit {
    public static String parseLines(final List<String> input) {
        final int rowCount = input.size();
        final var sb = new StringBuilder();
        for (int row = 0; row < rowCount; row += HEIGHT) {
            if (sb.length() > 0) sb.append(',');
            sb.append(parseLine(input, row));
        }
        return sb.toString();
    }

    private static String parseLine(
        final List<String> input,
        final int row) 
    {
        final int colCount = input.get(0).length();
        final var sb = new StringBuilder();
        for (int col = 0; col < colCount; col += WIDTH) {
            sb.append(parseOne(input, row, col));
        }
        
        return sb.toString();
    }

    private static String parseOne(
        final List<String> input,
        final int row,
        final int col)
    {
        for (int i = 0; i < ALL_DIGITS.length; i++) {
            final String[] digit = ALL_DIGITS[i];
            if (isMatch(digit, input, row, col)) {
                return Integer.toString(i);
            }
        }

        return "?";
    }

    private static boolean isMatch(
        final String[] example,
        final List<String> input,
        final int inputRow,
        final int inputCol)
    {
        for (int row = 0; row < HEIGHT; row++) {
            for (int col = 0; col < WIDTH; col++) {
                final char exampleChar = example[row].charAt(col);
                final char inputChar = input
                    .get(inputRow + row)
                    .charAt(inputCol + col);

                if (exampleChar != inputChar) {
                    return false;
                }
            }
        }

        return true;
    }

    private static final String[] ZERO = new String[] {
        " _ ",
        "| |",
        "|_|",
        "   ",
    };

    private static final int WIDTH = ZERO[0].length();
    private static final int HEIGHT = ZERO.length;

    private static final String[] ONE = new String[] {
        "   ",
        "  |",
        "  |",
        "   ",        
    };

    private static final String[] TWO = new String[] {
        " _ ",
        " _|",
        "|_ ",
        "   ",        
    };

    private static final String[] THREE = new String[] {
        " _ ",
        " _|",
        " _|",
        "   ",        
    };

    private static final String[] FOUR = new String[] {
        "   ",
        "|_|",
        "  |",
        "   ",        
    };

    private static final String[] FIVE = new String[] {
        " _ ",
        "|_ ",
        " _|",
        "   ",
    };

    private static final String[] SIX = new String[] {
        " _ ",
        "|_ ",
        "|_|",
        "   ",        
    };

    private static final String[] SEVEN = new String[] {
        " _ ",
        "  |",
        "  |",
        "   ",        
    };

    private static final String[] EIGHT = new String[] {
        " _ ",
        "|_|",
        "|_|",
        "   ",        
    };

    private static final String[] NINE = new String[] {
        " _ ",
        "|_|",
        " _|",
        "   ",        
    };    

    private static final String[][] ALL_DIGITS = new String[][] {
        ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE,
    };    
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?