Created
November 26, 2014 16:01
-
-
Save xmichaelx/fb9450ff8dedaf79a061 to your computer and use it in GitHub Desktop.
Simple implementation of binary, 1D cellular automaton with sample 184 rule (http://en.wikipedia.org/wiki/Rule_184)
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
from random import uniform | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from random import sample | |
n = 200 # number of cells in row | |
num_iters = 200 # number of iterations | |
density = 0.5 # how many positives | |
# rule 184 | |
rules = { | |
"111" : "1", "110" : "0", "101" : "1", "100" : "1", | |
"011" : "1", "010" : "0", "001" : "0", "000" : "0" | |
} | |
# generating randomized string with fixed number of positives | |
positives = int(n*density) | |
initial = ''.join(sample(["1" if i < positives else "0" for i in range(n)],n) ) | |
iterations = [initial] | |
# generating | |
for i in range(num_iters): | |
prev,curr = iterations[-1],"" | |
for j in range(n): | |
if (j > 0) and (j < n -1): | |
curr += rules[prev[j-1:j+2]] | |
elif j == 0: | |
curr += rules[prev[-1] + prev[0] + prev[1]] | |
elif j == n-1: | |
curr += rules[prev[-2] + prev[-1] + prev[0]] | |
iterations.append(curr) | |
# converting to matrix | |
a = np.zeros(shape=(num_iters,n)) | |
for i in range(n): | |
for j in range(num_iters): | |
a[j,i] = 1 if iterations[j][i] == "1" else 0 | |
# showing image | |
plt.imshow(a, cmap="Greys", interpolation="nearest") | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment