I have a 2d array and I want to check if its in increasing order.

here is a example of 2d array increasing order:

0,  1,  2,  3,  4,
5,  6,  7,  8,  9,
10, 11, 12, 13, 14,
15, 16, 17, 18, 19,
20, 21, 22, 23, 24,

here is what I have so far.

public class test{

   int a[][] = new int[5][5];
   boolean inOrder = false;


    // game loop
    public void gameloop(){ 
        //check if 2d array is increasing order
        for (int r = 0; r < a.length; r++) {
                for (int c = 0; c < a[0].length; c++) {
                    if(r != 5){ //make sure its not out of bond
                        if(a[r][c]  < a[r+1][c]){
                             inOrder = true;
                        }else{
                            incOrder = false;
                        }
                    }
                }
        }
    }

I get an error on line:

line: if(r != 5){
error: Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException: 5

if(r < (a.length-1)) {..}

When I run this than the inOrder is true even when array is not in inc order.

are you only checking vertical order or horizontal order too??

boolean inOrder = true;

//check if 2d array is increasing order
for (int r = 0; r < a.length; r++) {
    for (int c = 0; c < a[r].length; c++) {

        /* check horizontal ordering */
        if(c < a[r].length-1) {
            if(a[r][c] > a[r][c+1]) {
                inOrder = false;
                break; //break inner loop
            }
        }

        /* check vertical ordering */
        if(r < a.length-1){ 
            if(a[r][c] > a[r+1][c]){
                 inOrder = false;
                 break; //break inner loop
            } 
        } 
    }
    if(!inOrder)
        break; //break outer loop
}

another possible way: duplicate the array, and sort it. then, check whether both are equal.

How about something simpler like

    boolean isAscending(int[][] a) {
        int last = Integer.MIN_VALUE;
        for (int r = 0; r < a.length; r++) {
                for (int c = 0; c < a[r].length; c++) { 
                      if (a[r][c] <= last) {
                           return false
                      }
                      last = a[r][c];
                }
         }
         return true;
    }

ps: Interesting point re use of r and c as indexes. Nothing wrong with that, but if you mix it with any uses of x and y you get guaranteed confusion becauuase the order is reversed (row corresponds to y coord, col to x coord)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.