Skip to content

Instantly share code, notes, and snippets.

@omaraflak
Last active January 10, 2024 00:39
Show Gist options
  • Save omaraflak/d4bcab787ac96eedb3d8b0e93449342f to your computer and use it in GitHub Desktop.
Save omaraflak/d4bcab787ac96eedb3d8b0e93449342f to your computer and use it in GitHub Desktop.
Wolfram Cellular Automata
def print_cells(cells: list[int]):
print(''.join('■' if i == 1 else ' ' for i in cells))
def next_step(cells: list[int], rules: list[int]) -> list[int]:
new_cells: list[int] = [False] * len(cells)
for i in range(len(cells)):
left = cells[(i - 1) % len(cells)]
right = cells[(i + 1) % len(cells)]
idx = int(''.join([str(left), str(cells[i]), str(right)]), 2)
new_cells[i] = rules[idx]
return new_cells
def cellular_automata(rule: int, height: int = 40, width: int = 101):
rules = [int(i) for i in f'{rule:08b}'[::-1]]
cells = [0] * width
cells[width // 2] = 1
for _ in range(height):
print_cells(cells)
cells = next_step(cells, rules)
print_cells(cells)
# rules: https://mathworld.wolfram.com/ElementaryCellularAutomaton.html
cellular_automata(182, 50, 150)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment