84 lines
1.7 KiB
Plaintext
84 lines
1.7 KiB
Plaintext
ElementaryCellularAutomaton = {"state": null, "rules": [], "ruleNum": 0}
|
|
|
|
ElementaryCellularAutomaton.init = function(n, state)
|
|
oneD = new ElementaryCellularAutomaton
|
|
oneD.state = state.split("")
|
|
oneD.ruleNum = n
|
|
oneD.rules = oneD.__createRules(n)
|
|
return oneD
|
|
end function
|
|
|
|
ElementaryCellularAutomaton.__createRules = function(n)
|
|
bits = self.__bitString(n)
|
|
rules = []
|
|
for i in range(7,0)
|
|
if bits[7-i] == "*" then rules.push(self.__bitString(i,3))
|
|
end for
|
|
return rules
|
|
end function
|
|
|
|
ElementaryCellularAutomaton.__bitString = function(n, width = 8)
|
|
s = ""
|
|
while s.len < width
|
|
s = char(46 - (n % 2) * 4) + s
|
|
n = floor(n / 2)
|
|
end while
|
|
return s
|
|
end function
|
|
|
|
ElementaryCellularAutomaton.evolve = function
|
|
length = self.state.len
|
|
newState = []
|
|
for i in range(0, length - 1)
|
|
s = ""
|
|
for j in [-1,0,1]
|
|
s += self.state[(i + j + length) % length]
|
|
end for
|
|
if self.rules.indexOf(s) != null then
|
|
newState.push "*"
|
|
else
|
|
newState.push "."
|
|
end if
|
|
end for
|
|
self.state = newState
|
|
end function
|
|
|
|
ElementaryCellularAutomaton.getState = function
|
|
output = self.state.join("")
|
|
return output
|
|
end function
|
|
|
|
getAllStates = function(cells)
|
|
s = ""
|
|
for i in range(0, cells.len - 1)
|
|
s += " " + cells[i].getState
|
|
end for
|
|
return s
|
|
end function
|
|
|
|
// Main program
|
|
automata = []
|
|
startState = "." * 15 + "*" + "." * 15
|
|
|
|
s = " "
|
|
for i in [30,60,90]
|
|
s += " " * 13 + "Rule " + i + " " * 12
|
|
automata.push(ElementaryCellularAutomaton.init(i, startState))
|
|
end for
|
|
print s
|
|
|
|
for i in range(0, 99)
|
|
s = "0" * 2 + str(i)
|
|
s = s[-3:]
|
|
s += getAllStates(automata)
|
|
print s
|
|
for j in range(0, automata.len - 1)
|
|
automata[j].evolve
|
|
end for
|
|
end for
|
|
|
|
// display last evolution
|
|
s = "100"
|
|
s += getAllStates(automata)
|
|
print s
|