繁体   English   中英

从特定点检查二维数组中的邻居是否相同

[英]Checking if the neighbors are the same in a 2d array from a specific point

从特定点检查行中在各个方向上有多少个相同字符时,我遇到了一个问题。

例如,对它的测试将是:

assertEquals(2, game.getMaxSequence(0, 0, 0, 1, 'o'));
assertEquals(1, game.getMaxSequence(0, 0, 0, 1, 'x'));

我想出了从左上角开始的方法。 但是,当涉及到特定点并增加参数时,我迷失了。

这是签名:

getMaxSequence(int row, int column, int dr, int dc, char symbol)

谢谢您的帮助。

更新,我得到了

 public int getMaxSequence(int row, int column, int dr, int dc, char symbol) {
    int maxSequence = 0;
    char[] rows = new char[row];
    char[] columns = new char[column];


    for(int i = 0; i < rows.length; i++){
        for(int j = 0; j < dc; j++){
            for(int k = 0; k < dr; k++){

        if( rows[i] == symbol && columns[i] == symbol)
        {
            maxSequence++;//this should test to see if the index at this 
            //row is equal to what you pass it.
        }
        }
        }

}
    return maxSequence;
}

它仍然没有任何建议吗?

如果您在可视化方面遇到困难,这是一个简单的2D阵列。 索引从0n-1 ,其中n是数组的长度。

[0][0]            [0][n-1]
    ┌───┬───┬───┬───┐
    │   │   │   │   │
    ├───┼───┼───┼───┤
    │   │   │   │   │
    ├───┼───┼───┼───┤
    │   │   │   │   │
    ├───┼───┼───┼───┤
    │   │   │   │   │
    └───┴───┴───┴───┘
[n-1][0]          [n-1][n-1]

我们可以选择任意点(称为p ),并通过增加/减少索引来向任意方向行走(前提是我们必须位于0n-1的范围内)。

 [x--, y--]      [y--]       [x++, y--]
            ┌───┬───┬───┬───┐
            │   │   │   │   │
            ├───┼───┼───┼───┤
            │   │   │   │   │
   [x--]    ├───┼───┼───┼───┤   [x++]
            │   │ p │   │   │
            ├───┼───┼───┼───┤
            │   │   │   │   │
            └───┴───┴───┴───┘
 [x--, y++]      [y++]       [x++, y++]

一旦可以将其可视化,就可以轻松转换为循环。

char[][] arr = ... ;

// increments are -1, 0 or 1
int xIncrement = ... ;
int yIncrement = ... ;

// starting coordinates
int x = pX;
int y = pY;

while( ( y < arr.length ) && ( x < arr[y].length ) ) {

    char c = arr[y][x];

    // do something with c

    x += xIncrement;
    y += yIncrement;
}

您可以选择更复杂的语法(例如for循环, ++--等),但这是一个很好的基本形式。

在我的图中, p对应于索引[2][1] 如果我想从p转到[0][n-1] (“右上角”),则x增量为+1y增量为-1

暂无
暂无

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

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