gpt4 book ai didi

java - 在二维数组中查找重复数字

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:18:00 25 4
gpt4 key购买 nike

我有一个二维数组,我需要在其中以水平方式打印。即,从上到下对角线打印。

public class ArrayExample {

public static int[] array = new int[]{{2,1,0,3,1,6,1}, {2,1,0,3,1,6,1},{2,1,0,3,1,6,1},{2,1,0,3,1,6,1}};
public static void main(String[] args) {
printArray(4,4);
}

private static printArray(int row, column){
for (int i=0; i < row; i++){
for (int j=0; i<column;j++){
System.out.print(array[i][j]);
}
System.out.println();
}
}
}

但是我需要对角打印。能否请您告诉我我可以用 Java 语言编写的伪代码。

最佳答案

要比较两条对角线,您可以像这样简化您的逻辑:

//This loop is to check the constructiveness for left-right diagonal.
//Because all the diagonal element will have same indexes, so (i,i) can be used.
int temp = matrix[0][0];
int counter = 0;
for (int i=0; i<n; i++) {
if(matrix[i][i] == temp) {
counter++;
}
else {
temp = matrix[i][i];
}
if(counter == consecutiveTimes) {
break;
}
}

//This loop is to check the constructiveness for right-left diagonal.
//Here sum of all the row index and column index will be n-1. n is the size of your square matrix.
int temp = matrix[0][n-1];
int counter = 0;
for(int i=0; i<n; i++) {
if(matrix[i][n-1-i] == temp) {
counter++;
}
else {
temp = matrix[i][n-1-i];
}
if(counter == consecutiveTimes) {
break;
}
}

关于java - 在二维数组中查找重复数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32470367/

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