Z
Z
Zlaylink2016-08-11 09:08:13
Java
Zlaylink, 2016-08-11 09:08:13

Why is the result of the code different?

There is a method that finds the rectangles in the matrix, the first one gives the correct result, after trying to write the If-else branch into one condition, I catch java.lang.ArrayIndexOutOfBoundsException: -1.

public static int getRectangleCount(byte[][] a)
    {
        int count = 0;
        for (int j = 0; j < a.length; j++) {
            for (int i = 0; i < a.length; i++) {
                if (a[i][j] == 1) {
                    if (i == 0){
                        if (j == 0) {
                            count++;
                        } else if (a[i][j - 1] == 0) {
                            count++;
                        }
                    } else if (a[i - 1][j] == 0) {
                        if (j == 0){
                            count++;
                        } else if (a[i][j - 1] == 0) {
                            count++;
                        }
                    }
                }
            }
        }
        return count;
    }


public static int getRectangleCount(byte[][] a)
    {
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a.length; j++) {
                if (a[i][j] == 1 && ((i == 0 && (j == 0 || a[i][j-1] == 0)) || (a[i-1][j] == 0 && (j == 0 || a[i][j-1] == 0)))) {
                    count++;
                }
            }
        }
        return count;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Yakushev, 2016-08-11
@Zlaylink

In my opinion, you messed up with cycles: your array is two-dimensional, but in both cycles you ask for the length of only one of the indices. But inside in the conditions you mean the use of both indexes. It is quite possible that you do not catch the error in the first version of the code due to the fact that you use a different order of cycles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question