我有几种方法可以运行Conway的生活游戏,但是在我的邻居计数方法中,我不知道如何解决环绕问题。我将提出实现此目的的方法。
同样,我主要只是需要我的neighborCount方法的帮助。我已经测试了其他方法,它们似乎工作得很好,但是当我测试问题方法时,它实际上返回了虚假值。

public class GameOfLife {

private boolean[][] society;
private boolean cell = true;
private boolean empty = false;

public GameOfLife(int rows, int cols) {
    // Complete this method.
    society = new boolean[rows][cols];
    for (int r = 0; r < society.length; r++) {
        for (int c = 0; c < society[0].length; c++) {
            society[r][c] = empty;
        }
    }
}
public void growCellAt(int row, int col) {
    // Complete this method
    society[row][col] = cell;
}
public int neighborCount(int row, int col) {
    int count = 0;
    for (int r = 0; r < society.length; r++) {
        for (int c = 0; c < society[0].length; c++) {
            // up and left
            if (society[(r - 1 + row) % row][(c - 1 + col) % col] == cell) {
                count++;
            }
            // up
            if (society[(r - 1 + row) % row][c] == cell) {
                count++;
            }
            // up and right
            if (society[(r - 1 + row) % row][(c + 1 + col) % col] == cell) {
                count++;
            }
            // right
            if (society[r][(c + 1 + col) % col] == cell) {
                count++;
            }
            // down and right
            if (society[(r + 1 + row) % row][(c + 1 + col) % col] == cell) {
                count++;
            }
            // down
            if (society[(r + 1 + row) % row][c]){
                count++;
            }
            // down and left
            if (society[(r + 1 + row) % row][(c - 1 + col) % col] == cell) {
                count++;
            }
            // left
            if (society[r][(c - 1 + col) % col] == cell) {
                count++;
            }
        }
    }
    return count;
}


}

最佳答案

您的模数似乎使用了错误的值。尽管很难说,因为该函数内部的逻辑有点奇怪。

如果rowcol是要测试的单元格的索引(它们似乎在其他位置),则肯定是错误的。您需要根据实际的行长和列长进行修改。即

society[(r - 1 + row) % society.length][(c - 1 + col) % society[0].length]


注意,对负数取模通常不是一个好主意。我不知道这是否适用于Java,但通常的方法是避免它们。为了解决这个问题:

(r + society.length - 1 + row) % society.length
(c + society[0].length - 1 + col) % society[0].length

08-17 19:44
查看更多