首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在康威的“生命游戏”中,如何计算牢房的活邻居?

在康威的“生命游戏”中,如何计算牢房的活邻居?
EN

Stack Overflow用户
提问于 2012-09-19 09:42:38
回答 3查看 5.4K关注 0票数 1

我在执行康维的生活游戏。我已经在黑板上读过了,现在我需要对它进行编程,以计数一个牢房的活邻居。

一些基本规则

任何活的细胞,如果少于两个活的邻居,就会死亡,就好像是由人口不足引起的。任何有两三个活邻居的活细胞都会活到下一代。任何有三个以上活邻居的活牢房都会死,好像是过度拥挤所致。任何有三个活邻居的死细胞都会变成活细胞,就像通过繁殖一样。

这是我已经有的密码。

更新:这是一些初始建议后修改的代码。

代码语言:javascript
复制
/**
 * Write your comments here following the javadoc conventions
 */
public static int countNeighbours(boolean[][] board, int row, int col)
{
    int neighbours = 0; 
    int x = -1;
    while (x <= 1) {
        int y = -1;
        while (y <= 1) {
            if (board[row][col] == true) {

                neighbours++; 
            }
            // Given a 2D boolan array and a cell location given by its
            // row and column indecies, count the number of live cells
            // immediately surrounding the given cell. Remember that you
            // mustn't count the cell itself.

        }


    }
    return neighbours;
}

这条路是对的吗?

EN

回答 3

Stack Overflow用户

发布于 2012-09-19 09:45:58

我觉得你想做

代码语言:javascript
复制
if (board[row][col] == true) {

这与

代码语言:javascript
复制
if (board[row][col]) {
票数 2
EN

Stack Overflow用户

发布于 2012-09-19 09:49:28

因为我知道这是一个典型的学校作业,所以我想给你一个完整的答案,但是你不应该在方法的开头修改行,叫它别的,循环应该从row-1row+1col-1col+1

票数 2
EN

Stack Overflow用户

发布于 2015-01-29 06:29:37

如果您可以使您的板是全局的,这可能适用于一个带环绕的单个单元格:

代码语言:javascript
复制
public Cell[] getNeighbours(int i, int j) {
int i2 = i - 1, i3 = i + 1, j2 = j - 1, j3 = j + 1;
if (i2 == -1) i2 = board.length - 1;
if (i3 == (board.length)) i3 = 0;
if (j2 == -1) j2 = board[i].length - 1;
if (j3 == (board[i].length)) j3 = 0;
return new Cell[]{board[i2][j2], board[i2][j], board[i2][j3], board[i][j2], board[i][j3], board[i3][j2], board[i3][j], board[i3][j3]};

}

然后数一数这些细胞中有多少活了回来。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12492196

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档