gpt4 book ai didi

python - 生成规则 30 元胞自动机的行

转载 作者:行者123 更新时间:2023-11-30 21:52:59 25 4
gpt4 key购买 nike

规则 30 是一个一维元胞自动机,其中当前一代仅考虑上一代的细胞。单元格可以处于两种状态:10。创建下一代的规则在下面的行中表示,并取决于当前单元格上方的单元格及其直接邻居。

元胞自动机按以下规则应用(使用按位运算符):

left_cell ^ (central_cell | right_cell)

该规则形成下表:

enter image description here

现在我尝试使用 numpy 将这些规则实现到 Python 中。我定义了一个初始状态,它接受 width 作为参数,并生成初始的一行 0,中间有 1。

def initial_state(width):
initial = np.zeros((1, width), dtype=int)
if width % 2 == 0:
initial = np.insert(initial, int(width / 2), values=0, axis=1)
initial[0, int(width / 2)] = 1
return initial
else:
initial[0, int(width / 2)] = 1
return initial

下面的函数仅在给定初始行的情况下生成第二代。如何创建一个 for 循环,不断生成新的一代,直到最后一行的第一个元素变为 1?

def rule30(array):
row1 = np.pad(array,[(0,0), (1,1)], mode='constant')
next_row = array.copy()
for x in range(1, array.shape[0]+1):
for y in range(1, array.shape[1]+1):
if row1[x-1][y-1] == 1 ^ (row1[x-1][y] == 1 or row1[x-1][y+1] == 1):
next_row[x - 1, y - 1] = 1
else:
next_row[x - 1, y - 1] = 0
return np.concatenate((array, next_row))

例如,如果输入是

A = [0, 0, 0, 1, 0, 0, 0]

输出应该是

>>> print(rule30(A))
[[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 1, 1]]

最佳答案

这是基于字符串表示和查找的代码。它确实使用了上面评论中的一些想法。此外,我添加了用于处理边缘单元的填充 - 条件尚不清楚。另请注意,您建议的模式表不是对称的。比较“110”和“011”的新状态。

def rule30(a):
patterns = {'111': '0', '110': '0', '101': '0', '100': '1',
'011': '1', '010': '1', '001': '1', '000': '0', }
a = '0' + a + '0' # padding
return ''.join([patterns[a[i:i+3]] for i in range(len(a)-2)])

a = '0001000'
result = [list(map (int, a))]

while a[0] != '1':
a = rule30(a)
result.append (list(map (int, a)))
print (result) # list of lists
print (np.array(result)) # np.array

列表列表:

[[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1, 1]]

np.数组:

array([[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 1, 1]])

关于python - 生成规则 30 元胞自动机的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59773795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com