gpt4 book ai didi

java - 检查二维数组是否锯齿状

转载 作者:行者123 更新时间:2023-11-30 03:57:18 25 4
gpt4 key购买 nike

我正在完成一个程序,但在最后一个方面遇到了一些麻烦。

在程序的这一部分中,我正在测试数组是否呈锯齿状(行数和列数相同)。我想使用嵌套的 for 循环来执行此操作,但在逻辑和结构方面遇到问题。

例如,以下数组是锯齿状的:

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

下面的数组不是:

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

任何人都可以提供有关如何执行此操作的指导吗?

最佳答案

首先要清楚什么是锯齿状数组(坚持以二维数组作为典型情况):

  1. 技术上 a jagged array是一个(一维)数组的数组,每个数组可以具有不同的长度。
  2. 人们通常所说的“锯齿状数组”(我认为包括你在内)的意思是一个具有长度不同的(一维)数组元素的数组 - 即“< em>有效地锯齿状”。
  3. 最后,技术上是锯齿状但具有“相同行数和列数”的数组(实际上)是 square array .

(请注意,有效锯齿数组和有效方形数组是互斥的。)

您不需要嵌套的 for 循环来检查以下三个条件中的任何一个:

  • 凭借 int[][] 声明,条件 1 是不言而喻的。
  • 条件 2 和 3 需要 一个 for 循环 - 因为您不需要遍历包含可能不同长度数组的数组 可能不同长度的数组,只需迭代前者并检查后者的长度。

话虽如此,请考虑以下关于条件 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 ");
}
}

如果运行演示,您应该会看到以下输出:

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.

关于java - 检查二维数组是否锯齿状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com