The program is supposed to count from 0 to 19 and assign consecutive numbers, going through the matrix diagonally, as seen in the image:
I did it like this and it gives me the same result as in the image, but I don't think the method used is right.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner leer=new Scanner(System.in);
int a[][]=new int [4][5];
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length+1;j++){
a[1][0]=a[0][0]+1;
a[0][1]=a[1][0]+1;
a[2][0]=a[0][1]+1;
a[1][1]=a[2][0]+1;
a[0][2]=a[1][1]+1;
a[3][0]=a[0][2]+1;
a[2][1]=a[3][0]+1;
a[1][2]=a[2][1]+1;
a[0][3]=a[1][2]+1;
a[3][1]=a[0][3]+1;
a[2][2]=a[3][1]+1;
a[1][3]=a[2][2]+1;
a[0][4]=a[1][3]+1;
a[3][2]=a[0][4]+1;
a[2][3]=a[3][2]+1;
a[1][4]=a[2][3]+1;
a[3][3]=a[1][4]+1;
a[2][4]=a[3][3]+1;
a[3][4]=a[2][4]+1;
}
}
for(int i=0;i<a.length;i++){
System.out.println();
for(int j=0;j<a.length+1;j++){
System.out.print(a[i][j]+"\t");
}
}
}
Traverse a matrix
M x N
along the diagonalsIn an array
M x N
, let us consider the indices at each position in the array.There is a very interesting property: if we add the indices x + y, we get the number of each diagonal .
In this way, for each diagonal it has to be filled.
And the number of diagonals will always be
M + N - 1
.For example, for
4 x 5
,4 + 5 - 1 = 8
, there are 8 diagonals (from 0 to 7).So, we can iterate:
0
, while it is less thann + m - 1
.y = diagonal
to0
, withx = diagonal - y
.y
does not exceed its dimensionm
⇒
y
goes fromMath.min(diagonal,m - 1)
to0
x
does not exceed its dimensionn
⇒
x < n
num
after each assignment⇒
a[y][x] = num++;
.Code:
Result:
demonstration:
Ideone.com
The difficulty is that the expression best method is very subjective.
Now, if the criterion was that the algorithm that fills the matrix in diagonal sequences should work with matrices of any dimension , now yes, I can understand the need for a better method .
If that were the case, I would implement the algorithm like this (note that
dimX
anddimY
can be adjusted to change the dimension of the array):Result:
Still, I'm sure there are better methods .