[英]Java two-dimensional array filled with pattern
how can I fill two-dimensional array of given "size" to get this output: 如何填充给定“大小”的二维数组以获取此输出:
N=1 N = 1
000 000
010 010
000 000
N=2 N = 2
0000 0000
0110 0110
0110 0110
0000 0000
N=3 N = 3
00000 00000
01110 01110
01210 01210
01110 01110
00000 00000
public static void main (String[] args) throws java.lang.Exception
{
int x, y;
int N = 3;
int counter = 0;
x = y = N + 2;
int[][] array = new int[x][y];
for( int i = 0; i<x; i++){
for( int j = 0; j < y; j++){
if( i == 0 || i == x-1 || j == 0 || j == y-1){
array[i][j] = 0;
} else {
array[i][j] = 1;
}
System.out.print(array[i][j]);
}
System.out.println();
}
}
This code gives me just 1s surrounded by 0, but I cannot figure out how to increase value to the middle of array. 这段代码只给我1并被0包围,但是我无法弄清楚如何将值增加到数组的中间。 If N is an odd number I can use modulo, but i don't know how to do this with even numbers. 如果N是一个奇数,我可以使用模,但是我不知道该如何使用偶数。
The value of a cell is the shortest distance to the edge of the matrix. 像元的值是到矩阵边缘的最短距离。 assuming cell[i,j]
, this can be either 假设cell[i,j]
,可以是
so iterate over the matrix and calculate the shortest distance. 因此遍历矩阵并计算最短距离。
Here's your homework :-) 这是您的作业:-)
import static java.lang.Math.min;
public static void main (String[] args) throws java.lang.Exception {
int x, y;
int N = 5;
int counter = 0;
x = y = N + 2;
int[][] array = new int[x][y];
for (int i = 0; i < x; i++) {
counter = 0;
for (int j = 0; j < y; j++) {
if (i == 0 || i == x - 1 || j == 0 || j == y - 1) {
array[i][j] = 0;
} else {
array[i][j] = min(i,min(min(i,N-i+1),min(j,N-j+1)));
}
System.out.print(array[i][j]);
}
System.out.println();
}
}
It works by using 它可以通过使用
min(i,min(min(i,N-i+1),min(j,N-j+1)))
to calculate the shortest (minimum) distance to the edge. 计算到边缘的最短(最小)距离。 There are 4 quadrants in the matrix with each its own calculation of distance to edge - hence the four min
-operations. 矩阵中有4个象限,每个象限都有自己的到边缘的距离计算-因此有4个min
运算。
N=1: N = 1:
000
010
000
N=2: N = 2:
0000
0110
0110
0000
N=3: N = 3:
00000
01110
01210
01110
00000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.