简体   繁体   English

检查二维数组是否有锯齿

[英]Checking to see if a 2d array is jagged

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循环来执行此操作,但在逻辑和结构方面遇到问题。

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?任何人都可以提供有关如何执行此操作的指导吗?

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.从技术上讲锯齿状数组是一个 (1D) 数组的数组,每个数组可以有不同的长度。
  2. Often what people mean by "jagged array" (including you I think) is an array with (1D) array elements that do vary in length - ie " effectively jagged".通常人们所说的“锯齿形阵列”(包括你,我认为)是那些长短不一(1D)阵列元素的数组-即“有效锯齿”。
  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:您不需要嵌套for循环来检查以下三个条件中的任何一个:

  • Condition 1 is self-evident by virtue of a int[][] declaration.凭借int[][]声明,条件 1 是不言而喻的。
  • 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.条件 2 和 3 需要一个for循环 - 因为您不需要遍历包含潜在不同长度数组潜在不同长度数组的数组,只需遍历前者并检查后者的长度。

Having said this, consider the following IsJagged and IsSquare implementations and demo with respect to conditions 2 and 3:话虽如此,请考虑以下关于条件 2 和 3 的IsJaggedIsSquare实现和演示:

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.

If it's not totally required, why not use a for-each loop instead of a nested for loop?如果不是完全需要,为什么不使用 for-each 循环而不是嵌套的 for 循环? 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.重点是,我认为在嵌套的 for 循环上使用 for-each 循环会更容易使用。

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. Java 8 及更高版本。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM