我必须比较多维数组中的元素,以检查数字是水平还是垂直重复。我写了一个水平比较的程序。但是,一旦迭代了数组,如何更新current
值。请让我知道我哪里出错了。
public class TwoDimensionArray {
private static int rows = 4;
private static int columns = 4;
private static int array[][] = new int[][]{{4,3,9,1},{6,2,4,2},{5,4,5,2},{7,7,2,4}};
public static void main(String args[]){
printArray();
System.out.println("--------------------");
int counter=0;
int i=0;
int j = 0;
int current=array[i][j];
for ( i = 0; i<rows; i++){
for(j=0;j<columns; j++){
if(array[i][j]==current){
System.out.print("i > "+i+" j > "+j);
}
}
System.out.println();
}
}
private static void printArray(){
for (int i = 0; i < rows; i++){
for (int j = 0 ; j < columns; j++){
System.out.print(array[i][j]+ " ");
}
System.out.println();
}
}
}
答案 0 :(得分:2)
我有一个解决方案。结果包含符合您标准的每个数字:
import java.util.ArrayList;
import java.util.List;
public class TwoDimensionArray
{
static final int RIGHT = 0;
static final int DIAGONAL = 1;
static final int DOWN = 2;
private static int array[][] = new int[][] { { 3, 3, 9, 0 }, { 4, 3, 4, 0 }, { 4, 4, 3, 0 }, { 4, 7, 2, 3 } };
private static int array2[][] = new int[][] { { 0, 3, 9, 0, 5 }, { 0, 3, 4, 0, 5 }, { 0, 4, 3, 0, 5 },
{ 0, 7, 2, 3, 5 }, { 0, 1, 1, 1, 5 } };
public static void main(String args[])
{
printArray(array);
checkAndPrint(array);
System.out.println();
printArray(array2);
checkAndPrint(array2);
}
private static void checkAndPrint(int[][] array)
{
List<Integer> result = new ArrayList<Integer>();
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if (i == 0 || j == 0)
{
checkDirections(array, array[i][j], i, j, result);
}
}
}
System.out.println(result);
}
private static void checkDirections(int[][] array, int number, int row, int column, List<Integer> container)
{
checkDirection(array, number, row, column, container, RIGHT, 0);
checkDirection(array, number, row, column, container, DIAGONAL, 0);
checkDirection(array, number, row, column, container, DOWN, 0);
}
private static void checkDirection(int[][] array, int number, int row, int column, List<Integer> container,
int direction, int count)
{
if (count == array.length - 1)
{
container.add(number);
}
int nextI = row;
int nextJ = column;
switch (direction)
{
case RIGHT:
nextI++;
break;
case DIAGONAL:
nextI++;
nextJ++;
break;
case DOWN:
nextJ++;
break;
default:
break;
}
if (nextI < array.length && nextJ < array.length && array[nextI][nextJ] == number)
{
checkDirection(array, number, nextI, nextJ, container, direction, count + 1);
}
}
private static void printArray(int[][] array)
{
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();
}
}
}
输出:
3 3 9 0
4 3 4 0
4 4 3 0
4 7 2 3
[3]
0 3 9 0 5
0 3 4 0 5
0 4 3 0 5
0 7 2 3 5
0 1 1 1 5
[0, 5]
它只是检查线条和列以及从左上角到右边的对角线,但我认为您可以使用递归方法。