我在执行康维的生活游戏。我已经在黑板上读过了,现在我需要对它进行编程,以计数一个牢房的活邻居。
一些基本规则
任何活的细胞,如果少于两个活的邻居,就会死亡,就好像是由人口不足引起的。任何有两三个活邻居的活细胞都会活到下一代。任何有三个以上活邻居的活牢房都会死,好像是过度拥挤所致。任何有三个活邻居的死细胞都会变成活细胞,就像通过繁殖一样。
这是我已经有的密码。
更新:这是一些初始建议后修改的代码。
/**
* 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;
}这条路是对的吗?
发布于 2012-09-19 09:45:58
我觉得你想做
if (board[row][col] == true) {这与
if (board[row][col]) {发布于 2012-09-19 09:49:28
因为我知道这是一个典型的学校作业,所以我想给你一个完整的答案,但是你不应该在方法的开头修改行,叫它别的,循环应该从row-1到row+1,col-1到col+1。
发布于 2015-01-29 06:29:37
如果您可以使您的板是全局的,这可能适用于一个带环绕的单个单元格:
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]};}
然后数一数这些细胞中有多少活了回来。
https://stackoverflow.com/questions/12492196
复制相似问题