trim method
Trims the matrix by removing empty rows and columns from all sides.
Returns a new trimmed Artifact, or an empty one if there is no content.
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;
}