Java - 二维数组检查对角数字板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36395398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - 2D array checking diagonal number board
提问by Flinze
Currently I'm working on a program that generates random 0's and 1's in a 8x8 2D array board. What I have to do is check whether or not if all the numbers on the diagonal are the same (starting from the corners, not just any diagonals)
目前我正在开发一个在 8x8 2D 阵列板中生成随机 0 和 1 的程序。我要做的是检查对角线上的所有数字是否都相同(从角落开始,而不仅仅是任何对角线)
example:
例子:
int[][] array = {
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 1, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 1, 0}
};
So if by chance all the numbers starting from the top left corner (0,0),(1,1)...(7,7) are all either 0's or 1's then I have to output to the scanner indicating that "There is a major diagonal of 0" (from the example above).
因此,如果碰巧从左上角 (0,0),(1,1)...(7,7) 开始的所有数字都是 0 或 1,那么我必须输出到扫描仪,表明“那里是 0" 的主对角线(来自上面的示例)。
Also from this example, we can see that from the top-right, the number "1" is repeated diagonally towards the bottom left, then I also have to display "There is a minor diagonal of 1".
同样从这个例子中,我们可以看到,从右上角,数字“1”向左下角对角重复,然后我还必须显示“有一个小对角线 1”。
So far I have figured out how to generate and input the numbers into the array, but I don't know how to check. This is what I have so far:
到目前为止,我已经弄清楚如何生成数字并将其输入到数组中,但我不知道如何检查。这是我到目前为止:
public class javaTest{
// Main method
public static void main(String[] args) {
int[][] array = {
{0, 0, 0, 0, 0, 0, 0, 1},
{0, 0, 1, 0, 1, 0, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 0, 0, 1, 1, 1, 0},
{0, 0, 1, 1, 0, 1, 1, 0},
{0, 0, 1, 0, 0, 0, 1, 0},
{0, 1, 0, 0, 0, 0, 0, 0},
{1, 0, 0, 1, 1, 1, 1, 0}
};
// Print array numbers
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
System.out.print(array[i][j] + " ");
System.out.println();
}
// Print checkers
checkMajorDiagonal(array);
}
// Check major diagonal
public static void checkMajorDiagonal(int array[][]) {
int majDiag;
boolean isMatching = true;
int row = 0;
for(row = 0; row < array.length; row++){
majDiag = row;
if(array[row][row] != array[row+1][row+1]){
isMatching = false;
break;
}
}
//If all elements matched print output
if(isMatching)
System.out.println("Major diagnol is all " + array[row][row]);
}
}
Though what I have so far is not working as I want it to be as there is an error, and I still have to do the minor diagonal. Thanks in advance.
尽管到目前为止我所拥有的并没有像我想要的那样工作,因为存在错误,但我仍然需要做小对角线。提前致谢。
采纳答案by rgamber
There are a bunch of answers already. Here is one more way to do it. You are on the right track, but there is no need to complicate things by checking a diagonal element with the next element and so on. Just check each diagonal element with the first diagonal element. The moment you find a difference, you stop checking!
已经有一堆答案了。这是另一种方法。你在正确的轨道上,但没有必要通过检查对角线元素和下一个元素等等来使事情复杂化。只需用第一个对角线元素检查每个对角线元素。一旦发现差异,就停止检查!
public static void checkDiagonal(int[][] array){
// Start with the assumption that both diagonals are consistent.
boolean majorConsistent = true;
boolean minorConsistent = true;
int length = array.length;
int tempMajor = array[0][0]; // all elements in the Major must be equal to this
int tempMinor = array[0][length-1]; // all elements in the Minor must be equal to this
// Check major diagonal, and update the boolean if our assumption is wrong.
for(int i=0; i<length; i++){
if (array[i][i] != tempMajor) { //(0,0);(1,1);(3,3);...
majorConsistent = false;
break;
}
}
// Check minor diagonal, and update the boolean if our assumption is wrong.
for(int i=0,j=length-1; i<length; i++,j--){
if (array[i][j] != tempMinor) { //(0,7);(1,6);(2,5);...
minorConsistent = false;
break;
}
}
System.out.println("Major elements all same = "+majorConsistent);
System.out.println("Minor elements all same = "+minorConsistent);
}
This way you are still doing both the checks in O(n)and you don't need nested for loops! Notethat you can refine this code to remove redundancy i.e. have a single for loop, etc.
这样你仍然在O(n) 中进行检查,并且不需要嵌套 for 循环!请注意,您可以改进此代码以消除冗余,即具有单个 for 循环等。
回答by nhouser9
The error probably comes from the fact that you loop while row < array.length but you index into array[row+1]. This will result in an out of bounds exception.
错误可能来自这样一个事实,即您在 row < array.length 时循环,但您索引到 array[row+1]。这将导致越界异常。
For checking the minor diagonal, try something similar:
要检查次对角线,请尝试类似的操作:
int maxIndex = array.length - 1;
for(row = 0; row < maxIndex; row++){
majDiag = row;
if(array[row][maxIndex - row] != array[row+1][maxIndex - (row+1)]){
isMatching = false;
break;
}
}
回答by Naman
Some points about your method checkMajorDiagonal
:
关于你的方法的一些要点checkMajorDiagonal
:
int majDiag;
boolean isMatching = true;
int row = 0;
for(row = 0; row < array.length; row++){
majDiag = row; //not being used anywhere
if(array[row][row] != array[row+1][row+1]){ //out of bounds with row+1
isMatching = false;
break;
}
}
You can remove the unused majDiag
variable and change the loop code as
您可以删除未使用的majDiag
变量并将循环代码更改为
for(row = 0; row < array.length-1; row++)
Minor diagonal logic :
小对角逻辑:
for(row = 0; row < array.length; row++){
for(col = 0; col < array[i].length; col++){
if(row+col==array[i].length){
array[row][col] // this would be your minor diagonal element row wise
}
}
回答by sprinter
If you are using Java 8 then you could potentially do this with streams rather than iterating through the values manually. That might be a more direct approach than checking against previous values.
如果您使用的是 Java 8,那么您可能会使用流来执行此操作,而不是手动遍历值。这可能是比检查以前的值更直接的方法。
if (IntStream.range(0, size).map(n -> array[n][n]).allMatch(n -> n == 0)) {
}
if (IntStream.range(0, size).map(n -> array[n][size-n-1]).allMatch(n -> n == 1)) {
}
回答by Danyal Sandeelo
int diagonalValue = 0;
for(int i = 0; i < 8 ; i++){
diagonalValue = array[i][j];
for(int j = 0; j < 8 ; j++)
if(i==j){
if(array[i][j]==diagonalValue){
counter++;
}
else
break;
}
}
}
if(counter==8) // yes they are same else not
keep size of array i.e. 9 in a variable to make it loosely coupled.
保持数组的大小,即 9 在一个变量中,使其松散耦合。