I'm attempting to write a (hopefully) efficient way of "expanding" a 2d array into a 1d array. Let me illustrate what I mean:
Given the 2d array
{{1, 2},
{3, 4}}
and a block width of 2 and a block height of 2, we can "expand" into a 1d array
{1, 1, 2, 2, 1, 1, 2, 2, 3, 3, 4, 4, 3, 3, 4, 4}
Notice, if newlines are added this looks like
{1, 1, 2, 2,
1, 1, 2, 2,
3, 3, 4, 4,
3, 3, 4, 4}
And the original has been "expanded"!
The code I have currently is
public int[] expand(int[][] src, int blockWidth, int blockHeight) {
int[] dest = new int[src.length * src[0].length * blockWidth * blockHeight];
for (int i = 0; i < src.length; i++) {
for (int j = 0; j < src[i].length; j++) {
int fromIndex = i * blockWidth * blockHeight * src[i].length + j * blockWidth;
int toIndex = fromIndex + blockWidth;
Arrays.fill(dest, fromIndex, toIndex, src[i][j]);
}
int srcPos = i * blockWidth * blockHeight * src[i].length;
for (int k = 1; k < blockHeight; k++) {
int destPos = srcPos + k * blockWidth * src[i].length;
System.arraycopy(dest, srcPos, dest, destPos, src[i].length * blockWidth);
}
}
return dest;
}
This method:
- Creates the destination array equal to the total size of the source array times the block dimensions.
- For each color in a row, fill the first row of the destination.
- Copy the first row into the rest of the rows, completing the blocks.
I wonder if there's a way to make this method more efficient or cleaner?
Thanks!