this is the code to print the anti diagonal of a 2d array, if given the array
{{1,2,3}, {4,5,6}, {7,8,9}}
it should return
`{
{1},
{2,4},
{3,5,7},
{6,8},
{9}
}`
this is the code:
public static int[][] antiDiagonal(int [][]x){
int[][]res = new int[2*x.length-1][];
int s = 0;
for( int i = 0 ; i < res.length ; i++ ) {
if(i<= res.length/2)
s = i+1;
else
s = s -1;
res[i] = new int[s];
for( int j = i, r = 0 ; j >= 0 && r < res[i].length ; j-- ) {
if( (i-j) < x.length && j < x.length ){
res[i][r] = x[i-j][j] ;
r++;
}
}
}
return res;
}
my brain just can not process what the inner for loop does,
for( int j = i, r = 0 ; j >= 0 && r < res[i].length ; j-- ) {
if( (i-j) < x.length && j < x.length ){
res[i][r] = x[i-j][j] ;
r++;
}
}
i just need explanation of what the inner for loop achieves before my sanity detoriates and your response would be gladly appreciated.
I can accomplish using an alternative solution with Arraylists but the sole purpose of the question was to use 2D arrays only. I have understood all parts of the code except the inner for loop.
The inner for loop takes the input array, traverse it in diagonnal and store each diagonal element in the new array.
i
is the current row of new array,
j
is used for traversing the input array and finds anti diagonnal element,
r
is the index of current column in the new array
j
start at i
and decrement at each iteration while r
increment, this makes the loop traverse the input array diagonnaly : from last row / first column to first row / last column
The if
statement check that the indices used to access the input array are within the bounds of the array, if it is in the bounds it assign the corresponding values of input array in the new array
You can try with an example and debug your code by stoping at each steps to follow and better understand the process.