One-dimensional cellular automata: Difference between revisions
Content added Content deleted
(added Icon example) |
|||
Line 1,018: | Line 1,018: | ||
end |
end |
||
</lang> |
</lang> |
||
An alternative approach is to represent the automaton as a string. The following |
|||
solution takes advantage of the implicit type coercions between string and numeric |
|||
values in Icon and Unicon. It also surrounds the automaton with a border of 'dead' |
|||
(always 0) cells to eliminate the need to special case the first and last cells in |
|||
the automaton. Although the main procedure displays up to the first 10 generations, |
|||
the evolve procedure fails if a new generation is unchanged from the previous, stopping |
|||
the generation cycle early. |
|||
<lang unicon>procedure main(A) |
|||
A := if *A = 0 then ["01110110101010100100"] |
|||
CA := show("0"||A[1]||"0") # add always dead border cells |
|||
every CA := show(|evolve(CA)\10) # limit to max of 10 generations |
|||
end |
|||
procedure show(ca) |
|||
write(ca[2:-1]) # omit border cells |
|||
return ca |
|||
end |
|||
procedure evolve(CA) |
|||
newCA := repl("0",*CA) |
|||
every newCA[i := 2 to (*CA-1)] := (CA[i-1]+CA[i]+CA[i+1] = 2, "1") |
|||
return CA ~== newCA # fail if no change |
|||
end</lang> |
|||
A couple of sample runs: |
|||
<pre>->odca |
|||
01110110101010100100 |
|||
01011111010101000000 |
|||
00110001101010000000 |
|||
00110001110100000000 |
|||
00110001011000000000 |
|||
00110000111000000000 |
|||
00110000101000000000 |
|||
00110000010000000000 |
|||
00110000000000000000 |
|||
->odca 01110110 |
|||
01110110 |
|||
01011110 |
|||
00110010 |
|||
00110000 |
|||
-></pre> |
|||
=={{header|J}}== |
=={{header|J}}== |