Math Adventures with Python
An Illustrated Guide to Exploring Math with Code
楽天ブックス(Kobo) 紀伊国屋書店(Kinoppy)
開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Python 3.7 (プログラミング言語)
- Processing 3 (プログラミング言語、統合開発環境、グラフィック機能)
Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART 3(BLAZING YOUR OWN TRAIL)、11(CELLULAR AUTOMATA)、EXERCISE 11-2(CHANGING THE RULE SET)、11-3(ZOOMING IN AND OUT)の解答を求めてみる。
コード
Python 3
w = 5
rows = 100
cols = 100
cells = []
n = 90
# [0, 1, 0, 1, 1, 0, 1, 0]
# 90以外の他の数値でも試せるような方法で
# rule_set = [int(d) for d in f'{n:0>8b}'] python2でf-stringは使えない
rule_set = [int(d) for d in '{:0>8b}'.format(n)]
def rules(a, b, c):
return rule_set[7 - sum([2 ** (2 - i) * o
for i, o in enumerate([a, b, c])])]
def generate():
global cells
for i, row in enumerate(cells):
for j in range(1, len(row) - 1):
left = row[j - 1]
me = row[j]
right = row[j + 1]
if i < len(cells) - 1:
cells[i + 1][j] = rules(left, me, right)
return cells
def setup():
global cells
size(960, 515)
cells = [[0 for _ in range(cols)]
for _ in range(rows)]
cells[0][cols // 2] = 1
cells = generate()
def draw():
global cells
background(255)
for i, cell in enumerate(cells):
for j, v in enumerate(cell):
if v == 1:
fill(0)
else:
fill(255)
rect(j * w - (cols * w - width) / 2, w * i, w, w)
def keyPressed():
global w, n
if key == CODED:
if keyCode == UP:
w += 1
elif keyCode == DOWN:
w -= 1
0 コメント:
コメントを投稿