我有一个二维数组 我需要使用Java复制2d数组的每一行和每一列,如下所示(覆盖现有值,而不创建新的列/行):
当前方法
for(int i = 0; i < result.get(z).getWidth()-2; i+=1)
{ for(int j = 0; j < result.get(z).getHeight()-2; j+=1)
{
x[i+1][j] = result.get(z).getRGB(i, j);
x[i][j+1] = result.get(z).getRGB(i, j);
x[i+1][j+1] = result.get(z).getRGB(i, j);
}
}
答案 0 :(得分:0)
替代方法:
private static void duplicateAlternates(int[][] matrix) {
for (int row = 0; row < matrix.length; row += 2)
for (int col = 1; col < matrix.length; col += 2)
matrix[row][col] = matrix[row][col - 1];
for (int row = 1; row < matrix.length; row += 2)
for (int col = 0; col < matrix.length; col++)
matrix[row][col] = matrix[row - 1][col];
}
测试
public static void main(String[] args) {
int[][] matrix = { { 10, 17, 200, 255, 0 },
{ 0, 199, 100, 30, 45 },
{ 250, 23, 177, 180, 79 },
{ 0, 9, 14, 150, 70 },
{ 50, 55, 187, 10, 233 } };
print(matrix);
duplicateAlternates(matrix);
print(matrix);
}
private static void print(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++)
System.out.printf(" %3d", matrix[row][col]);
System.out.println();
}
System.out.println();
}
输出
10 17 200 255 0
0 199 100 30 45
250 23 177 180 79
0 9 14 150 70
50 55 187 10 233
10 10 200 200 0
10 10 200 200 0
250 250 177 177 79
250 250 177 177 79
50 50 187 187 233
答案 1 :(得分:0)
使用if / else的另一种方法:
private static void duplicateAlternatesWithIfElse(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix.length; col++) {
if ((row - 1) % 2 == 0) {
matrix[row][col] = matrix[row - 1][col];
} else if ((col - 1) % 2 == 0) {
matrix[row][col] = matrix[row][col - 1];
}
}
}
}
使用主要功能进行测试:
public static void main(String[] args) {
int[][] twoDimArray = {
{ 10, 17, 200, 255, 0 },
{ 0, 199, 100, 30, 45 },
{ 250, 23, 177, 180, 79 },
{ 0, 9, 14, 150, 70 },
{ 50, 55, 187, 10, 233 }
};
printMatrix(twoDimArray);
duplicateAlternatesWithIfElse(twoDimArray);
printMatrix(twoDimArray);
}
输出:
10 17 200 255 0
0 199 100 30 45
250 23 177 180 79
0 9 14 150 70
50 55 187 10 233
10 10 200 200 0
10 10 200 200 0
250 250 177 177 79
250 250 177 177 79
50 50 187 187 233