trim method

Artifact trim()

Trims the matrix by removing empty rows and columns from all sides.

This method removes rows and columns that contain only false values from the edges of the matrix, effectively trimming it to the smallest possible size that contains all true values.

Returns: A new Matrix object that is a trimmed version of the original. If the original matrix is empty or contains only false values, it returns an empty Matrix.

Note: This method does not modify the original matrix but returns a new one.

Implementation

Artifact trim() {
  if (isEmpty) {
    return Artifact(0, 0);
  }
  // Find the boundaries of the content
  int topRow = 0;
  int bottomRow = rows - 1;
  int leftCol = 0;
  int rightCol = cols - 1;

  // Find top row with content
  while (topRow < rows) {
    bool hasContent = false;
    for (int x = 0; x < cols; x++) {
      if (cellGet(x, topRow)) {
        hasContent = true;
        break;
      }
    }
    if (hasContent) {
      break;
    }
    topRow++;
  }

  // Find bottom row with content
  while (bottomRow > topRow) {
    bool hasContent = false;
    for (int x = 0; x < cols; x++) {
      if (cellGet(x, bottomRow)) {
        hasContent = true;
        break;
      }
    }
    if (hasContent) {
      break;
    }
    bottomRow--;
  }

  // Find left column with content
  outer:
  while (leftCol < cols) {
    for (int y = topRow; y <= bottomRow; y++) {
      if (cellGet(leftCol, y)) {
        break outer;
      }
    }
    leftCol++;
  }

  // Find right column with content
  outer:
  while (rightCol > leftCol) {
    for (int y = topRow; y <= bottomRow; y++) {
      if (cellGet(rightCol, y)) {
        break outer;
      }
    }
    rightCol--;
  }

  // Crop the grid
  final Artifact result = Artifact(
    rightCol - leftCol + 1,
    bottomRow - topRow + 1,
  );
  for (int y = topRow; y <= bottomRow; y++) {
    for (int x = leftCol; x <= rightCol; x++) {
      result.cellSet(x - leftCol, y - topRow, cellGet(x, y));
    }
  }
  return result;
}