I have a program where I need to remove a set of rows from a byte[][]
array. I want to remove every row that has no zeroes in it. Right now I'm using the following methods:
public byte[][] checkRows(byte[][] grid) {
LinkedList<Integer> temp = new LinkedList<Integer>();
boolean willRemove = false;
for (int y = 0; y < grid.length; y++) {
boolean tempCheck = true;
for (int x = 0; x < grid[0].length; x++) {
if (grid[y][x] == 0) {
tempCheck = false;
break;
}
}
if (tempCheck) {
temp.add(y);
willRemove = true;
}
}
if (willRemove) {
int[] rowArray = convert(temp);
return removeRows(grid, rowArray);
}
return grid;
}
public byte[][] removeRows(byte[][] grid, int[] rows) {
int total = rows.length;
int current = 0;
byte[][] retGrid = new byte[grid.length][grid[0].length];
for (int i = total; i < grid.length; i++) {
if (current < total && i-total+current == rows[current]) {
current++;
}
//retGrid[i] = grid[i-total+current].clone();
System.arraycopy(grid[i-total+current], 0, retGrid[i], 0, xsize);
}
return retGrid;
}
public int[] convert(LinkedList<Integer> intList) {
int[] retArray = new int[intList.size()];
for (int i = 0; i < retArray.length; i++) {
retArray[i] = intList.get(i).intValue();
}
return retArray;
}
This gives me a reasonably fast way of removing rows from a 2D Array and replacing them with zero rows at the top of the array. Is there any faster way to achieve the same result?
If it's unclear what the script does, it's for removing full rows in a game of Tetris.
UPDATE: Using System.arraycopy()
instead of clone()
provides a 5% performance boost for small arrays.