Question

I am finishing up a program but having a bit of trouble with one last aspect.

In this part of the program, I am testing to see if the array is jagged (same number of rows and columns). I want to use a nested for loop to do this but am having trouble with the logic and structure.

For example, the following array is jagged:

1, 2, 3
4, 5, 6
7, 8, 9, 10

And the following array is not:

1, 2, 3
4, 5, 6
7, 8, 9

Can anyone offer guidance on how to do this?

Was it helpful?

Solution

Start with being clear about what a jagged array is (sticking to 2D arrays as the typical case):

  1. Technically a jagged array is an array of (1D) arrays, each of which can have a different length.
  2. Often what people mean by "jagged array" (including you I think) is an array with (1D) array elements that do vary in length - i.e. "effectively jagged".
  3. Finally, an array that is technically jagged but has the "same number of rows and columns" is (effectively) a square array.

(Notice that effectively jagged and effectively square arrays are mutually exclusive.)

You do not need nested for loops to check for any of these three conditions:

  • Condition 1 is self-evident by virtue of a int[][] declaration.
  • Conditions 2 and 3 necessitate one for loop - because you do not need to iterate through the array that contains the potentially different-length arrays and the potentially different-length arrays, just iterate through the former and check the lengths of the latter.

Having said this, consider the following IsJagged and IsSquare implementations and demo with respect to conditions 2 and 3:

public class IsJaggedDemo {
    private static boolean IsJagged(int[][] array) {
        boolean isJagged = false;

        if (array != null) {
            Integer lastLength = null;
            for (int i = 0; i < array.length; i++) {
                if (lastLength == null) {
                    lastLength = array[i].length;
                } else if (lastLength.equals(array[i].length)) {
                    continue;
                } else {
                    isJagged = true;
                    break;
                }
            }
        }

        return isJagged;
    }

    private static boolean IsSquare(int[][] array) {
        boolean isSquare = false;

        if (array != null) {
            for (int i = 0; i < array.length; i++) {
                if (array[i].length != array.length) {
                    break;
                } else if (i != array.length - 1) {
                    continue;
                } else {
                    isSquare = true;
                }
            }
        }

        return isSquare;
    }

    public static void main(String[] args) {
        int[][] a = null;
        int[][] b =
            new int[][] {
                new int[] { 1 }
            };
        int[][] c =
            new int[][] {
                new int[] { 1, 2, 3 },
                new int[] { 4, 5, 6 },
                new int[] { 7, 8, 9 }
            };
        int[][] d =
            new int[][] {
                new int[] { 1, 2, 3 },
                new int[] { 4, 5, 6 },
                new int[] { 7, 8, 9, 10 }
            };
        int[][] e =
            new int[][] {
                new int[] { 1, 2, 3 }
            };
        int[][] f =
            new int[][] {
                new int[] { 1, 2, 3 },
                new int[] { 4, 5, 6 },
                new int[] { 7, 8, 9 },
                new int[] { 9, 8, 7 }
            };

        System.out.printf(
                "a is %1$sjagged and is %2$ssquare.\r\n",
                IsJagged(a) ? "" : "not ",
                IsSquare(a) ? "" : "not ");
        System.out.printf(
                "b is %1$sjagged and is %2$ssquare.\r\n",
                IsJagged(b) ? "" : "not ",
                IsSquare(b) ? "" : "not ");
        System.out.printf(
                "c is %1$sjagged and is %2$ssquare.\r\n",
                IsJagged(c) ? "" : "not ",
                IsSquare(c) ? "" : "not ");
        System.out.printf(
                "d is %1$sjagged and is %2$ssquare.\r\n",
                IsJagged(d) ? "" : "not ",
                IsSquare(d) ? "" : "not ");
        System.out.printf(
                "e is %1$sjagged and is %2$ssquare.\r\n",
                IsJagged(e) ? "" : "not ",
                IsSquare(e) ? "" : "not ");
        System.out.printf(
                "f is %1$sjagged and is %2$ssquare.\r\n",
                IsJagged(f) ? "" : "not ",
                IsSquare(f) ? "" : "not ");
    }
}

If you run the demo, you should see the following output:

a is not jagged and is not square.
b is not jagged and is square.
c is not jagged and is square.
d is jagged and is not square.
e is not jagged and is not square.
f is not jagged and is not square.

OTHER TIPS

If it's not totally required, why not use a for-each loop instead of a nested for loop? I came across this question just a couple minutes ago and I thought the previous answer seemed a bit complicated, although totally correct.

I know this is a how-many-months-old question but here's the solution I just came up with:

public static boolean isJagged(int[][] arr)
{
    boolean result = false;
    // for each 1D array in the 2D array arr
    for (int[] a : arr)
    {
        if (a.length != arr[0].length)
            result = true;
    }

    return result;
}

If result is returned as false, the 2D array is not jagged, else it is true.

Tested below:

public static void main(String[] args)
{
    int[][] c =
        new int[][] {
            new int[] { 1, 2, 3 },
            new int[] { 4, 5, 6 },
            new int[] { 7, 8, 9 }
        };
    int[][] d =
        new int[][] {
            new int[] { 1, 2, 3 },
            new int[] { 4, 5, 6 },
            new int[] { 7, 8, 9, 10 }
        };
    if (isJagged(c))
        System.out.println("C is jagged");
    else
        System.out.println("C is not jagged");
    if (isJagged(d))
        System.out.println("D is jagged");
    else
        System.out.println("D is not jagged");
}

This prints:

C is not jagged
D is jagged

Point is, I think using a for-each loop over a nested for loop would be a lot less complicated to use.

In a rectangular 2d array, the number of elements in each row is the same, and in a jagged 2d array, it is not. In a square 2d array, the number of elements in each row is equal to the number of rows.

public static void main(String[] args) {
    int[][] arr1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9, 10}};
    int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    System.out.println(isJagged(arr1)); // true
    System.out.println(isJagged(arr2)); // false
    System.out.println(isSquare(arr2)); // true
}
static boolean isJagged(int[][] arr) {
    int rowLength = arr[0].length;
    for (int[] row : arr)
        if (row.length != rowLength)
            return true;
    return false;
}
static boolean isSquare(int[][] arr) {
    int length = arr.length;
    for (int[] row : arr)
        if (row.length != length)
            return false;
    return true;
}

See also: How do I remove a row and a column from a jagged 2d array?

Java 8 and above.

Check square:

public static boolean isSquare(int[][] arr) {
    return Arrays.stream(arr)
            .noneMatch(row -> row.length != arr.length);
}

Check jagged:

public static boolean isJagged(int[][] arr) {
    return Arrays.stream(arr)
            .anyMatch(row -> row.length != arr[0].length);
}

Use and negate others:

int[][] arr1 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9, 10}};
int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

boolean square = !isJagged(arr1);
boolean jagged = !isSquare(arr2);

Generic:

public static <T> boolean isSquare(T[][] arr) {
    return Arrays.stream(arr)
            .noneMatch(row -> row.length != arr.length);
}

public static <T> boolean isJagged(T[][] arr) {
    return Arrays.stream(arr)
            .anyMatch(row -> row.length != arr[0].length);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top