Cellular Automata
Publish date: Sep 27, 2021
What is?
Cellular automata are discrete, abstract computation systems. Here, it is just a nice code exercise.
Exercise
Provide code to draw any rule cellular automata
Code
#!/usr/bin/env python
import sys
from random import randint
def seed(n):
return [x * randint(0, 1) for x in [1] * n]
def sum(left, center, right):
return 4 * left + 2 * center + right
def next_row(rule_array, row):
result = []
for i in range(len(row)):
result.append(1 if sum(row[i-1], row[i], row[(i+1) % len(row)])
in rule_array else 0)
return result
def parse_rule(rule):
rules = list(str(bin(rule))[2:].rjust(8, '0'))
rules.reverse()
rules = [int(x) for x in rules]
result = []
for i in range(len(rules)):
if rules[i]:
result.append(i)
return result
def print_row(row):
print(" ".join(['*' if x else ' ' for x in row]))
def run(rule, arr, rows=100):
rule_array = parse_rule(rule)
print_row(arr)
new_arr = next_row(rule_array, arr)
for i in range(rows):
new_arr = next_row(rule_array, new_arr)
print_row(new_arr)
if __name__ == "__main__":
args = sys.argv[1:]
if len(args) < 3:
print('Missing parameters:')
print('python cellular_automata.py rule(0-256) rows(int) column(int)')
print('Example:')
print('python cellular_automata.py 110 80 80')
else:
rule = int(args[0])
rows = int(args[1])
columns = int(args[2])
run(rule, seed(columns), rows)
Sample of Rule 110
python cellular_automata.py 110 20 20
* * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * *
* * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * * * * * *
* * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * * * * * *
* * * * * * * * * * * *