【发布时间】:2017-08-25 19:20:21
【问题描述】:
所以我正在制作一个模拟 Life-like 元胞自动机的程序,但我在计算单元格的活邻居时遇到了一些问题。问题是我希望能够改变网格环绕的方式——也就是说,它是否从 从左到右(即圆柱形)环绕,从 从上到下 和 从左到右(即环形),或 根本不(即平坦)——我不知道如何制作我的方法考虑到这一点。这是我目前所拥有的:
public int getLiveNeighbors(int row, int col)
{
int count = 0;
// "topology" is an int that represents wraparound:
// 0 = flat; 1 = cylindrical; 2 = toroidal
int top = topology != 2 ? row - 1 : (row + ROWS - 1) % ROWS;
int bottom = topology != 2 ? row + 1 : (row + 1) % ROWS;
int left = topology != 0 ? (col + COLS - 1) % COLS : col - 1;
int right = topology != 0 ? (col + 1) % COLS : col + 1;
for (int r = top; r < bottom + 1; r++)
for (int c = left; c < right + 1; c++)
if (!(r == row && c == col) && getCell(r, c).equals(LIVE))
count++;
}
我认为,关键是for-loop 中的if-语句——必须有某种方法来检查r 和c 是否在网格的范围内,而请记住,“边界”的定义将根据网格是否/如何环绕而有所不同。在过去,我通过使用三个不同的集合(每个环绕设置一个)来解决这个问题,其中包含八个不同的 if 语句,以分别检查组成原始单元邻域的八个单元中的每一个;正如你可以想象的那样,它不是很漂亮,但至少它有效。
我不太擅长解释我自己的代码,所以我希望这不会太令人困惑——我自己也觉得有点胡思乱想(哈)。如果有人有任何问题,请随时提问!
【问题讨论】: