简体   繁体   English

我将如何创建一个检查数组中整数的循环?

[英]How would I create this loop that examines integers in an array?

What I am doing is creating a matrix with a set number of rows and columns, and I am filling that table with random integers from range of 0 to 9. What I want to do now is determine if there is a consecutive even integer that repeats four times next to each other in the table. 我正在做的是创建具有一定数量的行和列的矩阵,然后用0到9范围内的随机整数填充该表。我现在要确定是否有连续的偶数重复在表中彼此相邻四次。 For instance, something like this: 例如,如下所示:

2 5 8 7 1
3 2 9 4 7
5 1 2 0 3
8 0 1 2 7

In that table, two appear consecutively, diagonally from the first spot. 在该表中,两个从第一个点对角线连续出现。 It can also be like this: 也可以像这样:

9 5 3 7 0
2 5 7 3 1
8 5 0 2 9
4 5 1 7 5

In this table, five appear vertically down from the second spot. 在此表中,从第二个点垂直向下出现五个。

I have created the two-dimensional array as shown here: 我创建了二维数组,如下所示:

public static void main(String[] args) {
    int[][] randomTable = new int[5][5];
    for (int row = 0; row < randomTable.length; row++) {
        for (int column = 0; column < randomTable[row].length; column++) {
            randomTable[row][column] = (int)(Math.random() * 10 + 0);
            System.out.print(randomTable[row][column] + " ");
        }
        System.out.println();
    }       
}

When testing the array, if the array contains those four consecutive even integers as I detailed above, I need it to return true. 在测试数组时,如果数组包含如上所述的那四个连续的偶数整数,则需要它返回true。 I know I need to create a loop, but how would I do this? 我知道我需要创建一个循环,但是我该怎么做呢?

I would try recursion. 我会尝试递归。 Start in the upper left. 从左上方开始。 If you find a even number, recusively call a method that keeps track of the count, can only look left in the row or in the next lower row. 如果找到偶数,请回溯地调用跟踪计数的方法,该方法只能在该行或下一个较低的行中向左看。

Recursive signature might be: 递归签名可能是:

  int getMaxSameNeibors(int valueToMatch, int numberFoundSoFar,
        int[][] array, int currentIndex0, int currentIndex1){

  }

Challenge would be the following: 挑战如下:

2 5 8 7 1
3 2 9 4 7
2 2 2 0 3
8 0 1 5 7

There are 5 neighboring "2"s, but don't double count the one at 2,3 because it is a neighbor of 2,2 and 3,1. 有5个相邻的“ 2”,但不要重复计算2,3,因为它是2,2和3,1的邻居。 To do this you might need to pass a list of found positions to the recursion. 为此,您可能需要将找到的职位列表传递给递归。

EDIT 编辑

I realized this wouldn't work well for the below... 我意识到这不适用于以下情况...

2 5 8 7 1
3 2 2 2 7
3 3 2 0 3
8 0 1 5 7

Because of this you will need to check same row right one, one row up one position right and one row down (left 1, directly under 2 and right 1). 因此,您将需要检查同一行,右一,右上一排,右下一排(左1,在2的正下方,右1)。 Because of this, I think you need to pass the list of found value indexes. 因此,我认为您需要传递发现值索引的列表。

I might consider doing a recursive approach to this. 我可能会考虑对此采取递归方法。

You know that a 'match' of four could be up, down, left, right, and diagonally in both directions. 您知道,两个方向上的“匹配”可以是向上,向下,向左,向右和对角线。 This is largely inefficient, but the first thing to come to my mind: 这在很大程度上没有效率,但是我首先想到的是:

call a method check(int value, int j, int i, int deltaJ, int deltaI, int count); 调用方法check(int value, int j, int i, int deltaJ, int deltaI, int count); on every int in randomTable[][] randomTable[][]每个int

The loops that would cycle through the entire random number array: 将循环遍历整个随机数数组的循环:

for (int i = 0; i < randomTable.length; i++) {
    for (int j = 0; j < randomTable[i].length; j++) {
        boolean a = check(randomTable[i][j], j, i, 1, 0, 1); // move right 
        System.out.print(a ? "The number " + randomTable[i][j] + "is in a line!" : );
    }
}

Then, the recursive loop could look something like this: 然后,递归循环可能看起来像这样:

boolean check(int value, int j, int i, int deltaJ, int deltaI, int count) {
    if (count == 4) {
        return true;
    }

    try {
        if (randomTable[i + deltaI][j + deltaJ] == value) {
            return check(randomTable[i + deltaI][j + deltaJ], j + deltaJ, i + deltaI, deltaJ, deltaI, count + 1);
        } else {
            return false;
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        return false;
    }
}

Think about it, when would you want your test to return true? 考虑一下,您什么时候希望您的测试返回true? If there are an even number appearing consecutively in a row, or in a column, or diagonally. 如果在行,列或对角线中连续出现偶数。 If they all appear in the same row, they have the same row number and consecutive column numbers. 如果它们都出现在同一行中,则它们具有相同的行号和连续的列号。

Likewise, if they appear in the same column, they have the same column and consecutive rows. 同样,如果它们出现在同一列中,则它们具有相同的列和连续的行。 By extension, how do you think you'd treat the table's diagonals? 通过扩展,您如何看待桌子的对角线?

James Taylor's answer is probabbly the nicest, but also very complicated. 詹姆斯·泰勒的答案可能是最好的,但也很复杂。 if your matrix is always 5x5 then: 如果您的矩阵始终为5x5,则:

for each row or column: the elements 1, 2 and 3 must be the same to be a "hit". 对于每一行或每一列:元素1、2和3必须相同才能成为“匹配”。 Check this and if so, check if the element 0 or 4 is that number as well. 对此进行检查,如果是,请检查元素0或4是否也是该数字。 if so again, you have a hit 如果又是一次,你很成功

those would be 2 rather simple loops! 那将是2个相当简单的循环!

then you need two more loops for the diagonals going from top left to down right and going from top right to down left. 那么您还需要两个循环,以便对角线从左上角到右下角,再从右上角到左下角。 Both variants can hold 4 possible hits. 两种变体可以容纳4个可能的命中。 those loops arent too complicated either 这些循环也不会太复杂

if your matrix can be of dynamic size, then go with recursion or create loops that alsways check the current number and the following 3 如果您的矩阵可以是动态大小,则进行递归操作或创建始终检查当前数字和以下3个循环的循环

I would write a method which checks for a sequence of a given number in a given direction, given by a dx (direction x) and dy (direction y) parameter: 我将编写一种方法来检查给定方向上给定数字的序列,该方向由dx (方向x)和dy (方向y)参数给出:

boolean checkSequence(int[][] table, int number, int x, int y, int dx, int dy) {...}

Then you just need to determine, which directions there are and which positions have enough room for a sequence in that direction and check them for all even numbers. 然后,您只需确定存在哪些方向以及哪些位置在该方向上有足够的空间容纳序列,然后检查所有偶数。 Here is the code: 这是代码:

import java.util.Arrays;

public class Sequence
{
    // which axis is x and y and in which direction depends on your own preference,
    // just need to be consistent (applies to the whole program)
    static final int[][] directions = {{1,0},{1,1},{0,1}};

    static final boolean checkSequence(int[][] table, int number, int x, int y, int dx, int dy)
    {
        for(int i=0;i<4;i++) {if(table[y+dy*i][x+dx*i]!=number) return false;}
        return true;
    }

    public static void main(String[] args)
    {
        while(true)
        {
            int[][] randomTable = new int[5][5];
            for (int row = 0; row < randomTable.length; row++)
            {
                for (int column = 0; column < randomTable[row].length; column++)
                {
                    randomTable[row][column] = (int)(Math.random() * 10 + 0);
                }
            }
            for(int d=0;d<directions.length;d++)
            {
                int dx = directions[d][0];
                int dy = directions[d][1];
                // determine starting points where you have enough space to allow for a sequence at least 4 numbers long
                for(int y=0;y<randomTable.length-dy*3;y++)
                {
                    for(int x=0;x<randomTable[y].length-dx*3;x++)
                    {
                        for(int i=0;i<=10;i+=2)
                        {
                            if(checkSequence(randomTable, i, x, y,dx,dy))
                            {
                                for (int row = 0; row < randomTable.length; row++)
                                {
                                    for (int column = 0; column < randomTable[row].length; column++)
                                    {
                                        System.out.print(randomTable[row][column] + " ");
                                    }
                                    System.out.println();
                                }

                                System.out.println("Heureka! Found sequence of number "+i+
                                        " at position "+x+","+y+" in direction "+dx+" "+dy);
                                return;
                            }
                        }
                    }
                }
            }
        }
    }
}

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

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