将3x3 2D阵列插入9x9 2D阵列

时间:2015-02-25 03:26:58

标签: java arrays

我需要一个Java函数,它采用2D 3x3阵列并将其放入2D 9x9阵列的中心。例如,3x3阵列应如下所示:

{{1,2,3},
 {4,5,6},
 {7,8,9}}

,生成的9x9数组应如下所示:

{{0,0,0,0,0,0,0,0,0},    < OLD|NEW >   {{0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,1,2,3,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,4,5,6,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,7,8,9,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0},                   {0,0,0,0,0,0,0,0,0},
 {0,0,0,0,0,0,0,0,0}}                   {0,0,0,0,0,0,0,0,0}}

我该怎么做?

3 个答案:

答案 0 :(得分:1)

两个坐标的两个嵌套循环,将(x, y)复制到(x+3, y+3)

答案 1 :(得分:1)

您可以使用偏移量3来复制元素:

int[][] res = new int[9][9];
for (int i = 3; i < 6; i++) {
    for (int j = 3; j < 6; j++) {
        res[i][j] = arr[i - 3][j - 3];
    }
}

答案 2 :(得分:1)

for(int y = 0; y < 3; ++y)
    for(int x = 0; x < 3; ++x)
       array9x9[y+3][x+3] = array3x3[y][x];