Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding repeating numbers in a two dimensional array

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.

like image 756
zilcuanu Avatar asked May 02 '26 03:05

zilcuanu


1 Answers

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;
       }
    }
like image 183
YoungHobbit Avatar answered May 03 '26 17:05

YoungHobbit