Anonymous user
One-dimensional cellular automata: Difference between revisions
One-dimensional cellular automata (view source)
Revision as of 15:01, 29 January 2010
, 14 years agoAdded JavaScript
(Factor) |
(Added JavaScript) |
||
Line 739:
Output:
<pre>Generation 0: _###_##_#_#_#_#__#__
Generation 1: _#_#####_#_#_#______
Generation 2: __##___##_#_#_______
Generation 3: __##___###_#________
Line 748:
Generation 8: __##________________
Generation 9: __##________________</pre>
=={{header|JavaScript}}==
The example below expects an array of 1s or 0s, as in the example algorithm. It also adds dead cells to both ends, which aren't included in the returned next generation.
state[i-1] refers to the new cell in question, (old[i] == 1) checks if the old cell was alive.
<lang javascript>function caStep(old) {
var old = [0].concat(old, [0]); // Surround with dead cells.
var state = []; // The new state.
for (var i=1; i<old.length-1; i++) {
switch (old[i-1] + old[i+1]) {
case 0: state[i-1] = 0; break;
case 1: state[i-1] = (old[i] == 1) ? 1 : 0; break;
case 2: state[i-1] = (old[i] == 1) ? 0 : 1; break;
}
}
return state;
}</lang>
Example usage:
<lang javascript>alert(caStep([0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]));</lang>
shows an alert with "0,1,0,1,1,1,1,1,0,1,0,1,0,1,0,0,0,0,0,0".
=={{header|Logo}}==
|