優化算法(五)元胞自動機

import numpy as np
import matplotlib.pyplot as plt

# 空間大小
number = 200

# 細胞分佈
cells = np.zeros((number, number))
cells[int(number/2)][int(number/2)-1] = 1
cells[int(number/2)][int(number/2)] = 1
cells[int(number/2)][int(number/2)+1] = 1


# 繪圖
def paintCells(cells):
    x = []
    y = []
    length = len(cells)
    for i in range(length):
        for j in range(length):
            if cells[i][j] == 1:
                x.append(i)
                y.append(j)
    plt.xlim((0, length))
    plt.ylim((0, length))
    plt.plot(x, y, '.')
    plt.show()
    plt.cla()


# 統計
def countCells(cells, i, j):
    count = 0
    for m in range(i-1, i+2):
        for n in range(j-1, j+2):
            if cells[m][n] == 1:
                count += 1
    return count


# 更新
def updateCells(cells):
    length = len(cells)
    ncells = np.zeros((length, length))
    for i in range(1, length-1):
        for j in range(1, length-1):
            count = countCells(cells, i, j)
            if count == 2 or count == 3:
                ncells[i][j] = 1
    return ncells


paintCells(cells)
for _ in range(80):
    cells = updateCells(cells)
paintCells(cells)

初始
終末

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章