繁体   English   中英

计算矩阵中的邻居 - 康威生命游戏

[英]Counting Neighbors in Matrix - Conway Game of Life

对于每个矩阵元素,我想添加其所有相邻单元格的值。

从我的初始数组开始

board = np.array([[0, 1, 1],
                   [0, 1, 0],
                   [1, 0, 0]])

我的结果应该是:

([2,2,2],
 [3,3,3],
 [1,2,1])

我创建了一个函数并使用强力方法来查找其周围是否存在单元格。 如果是,请将值相加并返回总计。 我不确定我是否正确接近我的if语句。 它说的是以下错误

'具有多个元素的数组的真值是不明确的:使用a.any()或a.all()'

def count_living_neighbors(board):
    count = np.zeros(board.shape, dtype=int)
    #
    # YOUR CODE HERE
    #

    for row in range(len(board)):
        for column in range(len(board[row])):
            total = 0
            if (board[column - 1]).any() in board:
                total += board[row][column-1]
            if (board[column + 1]).any() in board:
                total += board[row][column+1]    
            if (board[row - 1]).any() in board:
                total += board[row-1][column]
            if (board[row + 1]).any() in board:
                total += board[row+1][column]
            if (board[row + 1] and board[column - 1]).any() in board:
                total += board[row+1][column-1]
            if (board[row - 1] and board[column - 1]).any() in board:
                total += board[row-1][column-1]
            if (board[row + 1] and board[column + 1]).any() in board:
                total += board[row+1][column+1]
            if (board[row - 1] and board[column + 1]).any() in board:
                total += board[row+1][column+1]

            count[row][column] = total         

    return count

你可以使用scipy.signal.convolvemode='same'

from scipy import signal

kernel = np.ones((3, 3), dtype=np.int8)
kernel[1, 1] = 0
print(signal.convolve(board, kernel, mode='same'))
[[2 2 2]
 [3 3 3]
 [1 2 1]]

kernel看起来像这样:

array([[1, 1, 1],
       [1, 0, 1],
       [1, 1, 1]], dtype=int8)

无论board的形状如何,都是一样的。 基本上, kernel指的是邻居的位置(相对于中心的0)。

试试scipy.signal.convolve2d

convolve2d( yourMatrix, np.ones((3,3))

应该做的伎俩

关于你的代码:你可能不太熟悉Python或numpy语法,所以我建议找一些教程来练习基础知识。 (board[column - 1]).any()如果列中有任何单元格存在,则(board[column - 1]).any()将为True,其他单位则为False。 之后,您正在测试是否包含True(如果列中的所有单元格都已死,则为False)包含在板内,该板始终为True。 所以你的if语句没有多大意义。

为了测试neihgbourhood中的一个单元是否存活,它看起来像下面的任何if语句:

if board[row-1][column - 1]  ==  1:
if board[row-1, column - 1]   ==  1: 
if board[row-1, column - 1] : #in Python 1 is True and 0 is False

话虽这么说,算你不应该费心的是还活着围绕一个点细胞的数量if在所有的语句,只需添加所有的周围值,死亡的细胞值得一0和活细胞的价值1个所以只有活细胞无论如何都会出现在伯爵。 更进一步,你的代码将非常缓慢,你永远不应该使用for循环迭代一个numpy数组,正确的做法是利用所谓的向量化操作,即在整个数组上应用的操作例如: board[:,1:]+board[:,:-1]将为您提供一个数组,其中包含左侧单元格和右侧单元格的总和,您可以计算每个单元格。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM