I have a two dimensional array in which I need print in horizontal manner.i.e, diagonally from top to bottom.
public class ArrayExample {
public static int[] array = new int[]{{2,1,0,3,1,6,1}, {2,1,0,3,1,6,1},{2,1,0,3,1,6,1},{2,1,0,3,1,6,1}};
public static void main(String[] args) {
printArray(4,4);
}
private static printArray(int row, column){
for (int i=0; i < row; i++){
for (int j=0; i<column;j++){
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
But I need to print diagonally. Could you please let me know the pseudocode that I can write in Java language.
To compare both the diagonal you can simplify your logic like this:
//This loop is to check the constructiveness for left-right diagonal.
//Because all the diagonal element will have same indexes, so (i,i) can be used.
int temp = matrix[0][0];
int counter = 0;
for (int i=0; i<n; i++) {
if(matrix[i][i] == temp) {
counter++;
}
else {
temp = matrix[i][i];
}
if(counter == consecutiveTimes) {
break;
}
}
//This loop is to check the constructiveness for right-left diagonal.
//Here sum of all the row index and column index will be n-1. n is the size of your square matrix.
int temp = matrix[0][n-1];
int counter = 0;
for(int i=0; i<n; i++) {
if(matrix[i][n-1-i] == temp) {
counter++;
}
else {
temp = matrix[i][n-1-i];
}
if(counter == consecutiveTimes) {
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With