【发布时间】:2015-09-05 00:19:00
【问题描述】:
我目前正在使用@Test 案例在 Eclipse 中开发 Conway 的 Game of life 程序。我的所有方法都通过了测试,除了 neighborCount 方法。我已经看到使用 for 循环的这种方法的帖子,并且由于某种原因它不适用于我的代码。
我试图通过仅使用 for 循环定位相邻单元格来环绕二维数组。在数完邻居后,我也无法更新新社会。如果有人可以查看我的代码并在我的方法中找到错误,将不胜感激。先感谢您。我已经附上了我的所有代码,以防我在影响neighborCount()的另一种方法中出现错误。
public class GameOfLife {
private int theRows;
private int theCols;
private char[][] society;
public GameOfLife(int rows, int cols) {
// Complete this method.
society = new char[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
society[r][c] = ' ';
}
}
theRows = rows;
theCols = cols;
}
public int numberOfRows() {
return theRows;
}
public int numberOfColumns() {
return theCols;
}
public void growCellAt(int row, int col) {
// Complete this method
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[r].length; c++) {
society[r][c] = 'o';
}
}
}
public boolean cellAt(int row, int col) {
if (society[row][col] == 'o') {
return true;
} else {
return false;
}
}
@Override
public String toString() {
String res = "";
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[r].length; c++)
res = res + society[r][c];
}
return res;
}
public int neighborCount(int row, int col) {
int count = 0;
for(int i = row - 1; i <= row + 1; i++) {
if (i >= 0 && i >= society.length)
for(int j = col - 1; j <= col + 1; j++)
if (j >= 0 && j >= society[i].length)
if (i != row || j != col)
if (society[i][j] == 'o')
count++;
}
return count;
}
public void update() {
// Complete this method
char[][] newSociety = new char[society.length][society[0].length];
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[r].length; c++)
newSociety[r][c] = society[r][c];
}
}
}
【问题讨论】:
-
关于代码的注释:toString() 方法太慢了,因为它逐个字符地增长字符串,并为每个字符重新分配字符串。考虑使用 StringBuilder。
-
哦,好吧,这是有道理的!感谢您添加@SergeRogatch
标签: java arrays for-loop conways-game-of-life