applyMaskPenaltyRule3 static method

int applyMaskPenaltyRule3(
  1. ByteMatrix matrix
)

Apply mask penalty rule 3 and return the penalty. Find consecutive runs of 1:1:3:1:1:4 starting with black, or 4:1:1:3:1:1 starting with white, and give penalty to them. If we find patterns like 000010111010000, we give penalty once.

Implementation

static int applyMaskPenaltyRule3(ByteMatrix matrix) {
  int numPenalties = 0;
  final array = matrix.bytes;
  final width = matrix.width;
  final height = matrix.height;
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      final arrayY = array[y]; // We can at least optimize this access
      if (x + 6 < width &&
          arrayY[x] == 1 &&
          arrayY[x + 1] == 0 &&
          arrayY[x + 2] == 1 &&
          arrayY[x + 3] == 1 &&
          arrayY[x + 4] == 1 &&
          arrayY[x + 5] == 0 &&
          arrayY[x + 6] == 1 &&
          (_isWhiteHorizontal(arrayY, x - 4, x) ||
              _isWhiteHorizontal(arrayY, x + 7, x + 11))) {
        numPenalties++;
      }
      if (y + 6 < height &&
          array[y][x] == 1 &&
          array[y + 1][x] == 0 &&
          array[y + 2][x] == 1 &&
          array[y + 3][x] == 1 &&
          array[y + 4][x] == 1 &&
          array[y + 5][x] == 0 &&
          array[y + 6][x] == 1 &&
          (_isWhiteVertical(array, x, y - 4, y) ||
              _isWhiteVertical(array, x, y + 7, y + 11))) {
        numPenalties++;
      }
    }
  }
  return numPenalties * _n3;
}