Skip to content

Instantly share code, notes, and snippets.

@yatt
Created April 15, 2011 13:38
Show Gist options
  • Save yatt/921704 to your computer and use it in GitHub Desktop.
Save yatt/921704 to your computer and use it in GitHub Desktop.
an algorithm implementation of simple dimentional cellular automaton
# coding: utf-8
# one dimensional cell automaton
import random
class Cell1Dim(object):
def __init__(self, rule, initializer):
# buffer
self.fore = initializer
self.back = [0] * len(initializer)
self.step = 0
self.rule = [(rule >> (7-i)) & 1 for i in range(8)]
def update(self):
for i in xrange(len(self.fore)):
j = (self[i-1]<<2) + (self[i]<<1) + self[i+1]
self.back[i] = self.rule[j]
self.fore = self.back[:]
self.step += 1
def __getitem__(self, i):
return self.fore[(i + len(self.fore)) % len(self.fore)]
def __repr__(self):
return "".join([" *"[c] for c in self.fore])
def main():
import sys, os
if len(sys.argv) < 2:
print 'usage: %s rule [turn]' % os.path.basename(__file__)
return
rule = None
n = 30
try:
rule = int(sys.argv[1])
assert 0 <= rule <= 255
except:
return
if len(sys.argv) > 2:
try:
n = int(sys.argv[2])
assert n >= 0
except:
print 'argument `turn\' must be non-negative integer'
return
a = Cell1Dim(rule, [random.randint(0,1) for i in range(80)])
for i in range(n):
print a
a.update()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment