-
-
Save yosemitebandit/4256278 to your computer and use it in GitHub Desktop.
Randomly generate automata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# commented version of a gist from @thenoviceoof | |
import os | |
import time | |
import random | |
# capture the screen size and find the middle-ish pixel | |
rows, columns = os.popen('stty size', 'r').read().split() | |
columns = int(columns) | |
middle = columns/2 | |
# init a state vector as wide as your screen | |
state = [0]*columns | |
state[middle] = 1 | |
# state 30 | |
# 30.. not sure what oof meant by that | |
# aha! he says he meant the venerable rule 30: http://en.wikipedia.org/wiki/Rule_30 | |
# this dict is how new states are formed from the old | |
n = {(0,0,0):0, | |
(0,0,1):1, | |
(0,1,0):1, | |
(0,1,1):1, | |
(1,0,0):1, | |
(1,0,1):0, | |
(1,1,0):0, | |
(1,1,1):0, | |
} | |
def rand_machine(): | |
# this recomputes the "n" dict above | |
l = [(0,), (1,)] | |
for i in range(2): | |
# (0,) + (0,) = (0,0) | |
# build up "l," the list of tuples | |
# eventually contains all permutations of [0,1]p3 like (0,1,0), (1,1,0), etc.. | |
l = [a+(0,) for a in l] + [a+(1,) for a in l] | |
d = dict() | |
for a in l: | |
# assign a random value to each permutation | |
d[a] = random.randint(0,1) | |
return d | |
while 1: | |
# the visuals - zeros in the state vector are spaces, ones will be # | |
print "".join([{0:" ", 1:"#"}[c] for c in state]) | |
# next line of state is initialized | |
next_state = [0]*columns | |
# each element dependent on past value of itself and values of prev and next elements | |
for i in range(columns-2): | |
# check the n dict to determine the result of a permutation | |
next_state[i+1] = n[tuple(state[i:i+3])] | |
state = next_state | |
# 40% chance of flipping a random value in the state vector | |
if random.random() < 0.4: | |
i = random.randint(0,columns-1) | |
state[i] = {0:1, 1:0}[state[i]] | |
# 1% chance of changing the state-maker | |
if random.random() < 0.01: | |
n = rand_machine() | |
# let's go | |
time.sleep(0.01) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe I meant http://en.wikipedia.org/wiki/Rule_30 by State 30?