计算细胞自动机的相邻细胞

时间:2015-09-25 08:11:47

标签: javascript arrays matrix conways-game-of-life

我写了一个关于Conway的快速JS实现。

为了计算与给定单元相邻的“实时”单元的数量,我手动检查8个单元中的每一个。

function getNeighbourCount(x, y){
    var intCount = 0;
    intCount = (getCell(x-1, y-1)? intCount+1 : intCount); //x-1, y-1
    intCount = (getCell(x, y-1)? intCount+1 : intCount);//x, y-1
    intCount = (getCell(x + 1, y-1)? intCount+1 : intCount);//x + 1, y-1
    intCount = (getCell(x-1, y)? intCount+1 : intCount);//x-1, y
    intCount = (getCell(x+1, y)? intCount+1 : intCount);//x+1, y
    intCount = (getCell(x-1, y+1)? intCount+1 : intCount);//x-1, y+1
    intCount = (getCell(x, y+1)? intCount+1 : intCount);//x, y+1
    intCount = (getCell(x+1, y+1)? intCount+1 : intCount);//x-1, y+1

    return intCount;
}

它有效,但看起来很笨重。还有另一种更优雅的技术来实现同样的目标吗?优选地,适用于不同内核大小的技术。

这是一个工作示例的小提琴: http://jsfiddle.net/3vpz14v7/

注意:

  • 游戏状态保存在2D布尔数组中(本例中为50 * 50)
  • getCell(x,y)返回包含coords的单元格的值。

2 个答案:

答案 0 :(得分:1)

您可以以更紧凑和可视的格式存储内核,例如

var kernel = [
  "111",
  "101",
  "111"]

然后您编写一个函数将其解码为对getCell的调用,使您的内核易于阅读和修改(" 1"表示"如果单元格在那里,则递增1位置还活着#34;)。

答案 1 :(得分:0)

将其转换为循环,然后将循环打包到求和语句中。使用上面的内核掩码。将单元格状态存储为True = alive,False = dead。然后,您可以在内核掩码和所选单元格上运行快速循环以生成邻居计数。下面的代码显示了一个单元矩阵4x4的示例(但只执行中间单元格,以免在边缘运行)。

cell = [[False, False, False, True],
        [False, True, True, False],
        [False, False, True, False],
        [True, True, False, True]]

count_mask = [[True, True, True],
              [True, False, True],
              [True, True, True]]

cellx = len(cell)
celly = len(cell[0])
kernelx = len(count_mask)
kernely = len(count_mask[0])

for x in range(1, cellx-1):
    for y in range(1, celly-1):
        live_count = sum([1 if cell[x+row-1][y+col-1] and count_mask[row][col] \
            else 0 for row in range(kernelx) for col in range(kernely)])

        print live_count

结果输出

2
3
5
4

当然,如果您愿意,可以在新矩阵中捕获它 通过将总和循环放入 reduce 调用,您也可以更加Pythonic;我这样离开了,因为大多数程序员都可以使用它。

这足以让你前进吗?

相关问题