One-dimensional cellular automata: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
(Updated to compile with Nim 1.4. Changed indentation and identifiers to conform to guidelines. Added missing call to procedure.) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(41 intermediate revisions by 21 users not shown) | |||
Line 15:
1'''1'''0 -> 1 # Needs one neighbour to survive
1'''1'''1 -> 0 # Starved to death.
;Related tasks:
* [[Elementary_cellular_automaton|Elementary cellular automaton]]
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V gen = ‘_###_##_#_#_#_#__#__’.map(ch -> Int(ch == ‘#’))
L(n) 10
print(gen.map(cell -> (I cell != 0 {‘#’} E ‘_’)).join(‘’))
gen = [0] [+] gen [+] [0]
gen = (0 .< gen.len - 2).map(m -> Int(sum(:gen[m .+ 3]) == 2))</syntaxhighlight>
{{out}}
<pre>
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________
</pre>
=={{header|8th}}==
<
\ one-dimensional automaton
Line 50 ⟶ 76:
bye
</syntaxhighlight>
=={{header|ACL2}}==
<
(if (endp (rest cells))
nil
Line 85 ⟶ 111:
nil
(prog2$ (pretty-row (first out))
(pretty-output (rest out)))))</
=={{header|Action!}}==
<syntaxhighlight lang="action!">CHAR FUNC CalcCell(CHAR prev,curr,next)
IF prev='. AND curr='# AND next='# THEN
RETURN ('#)
ELSEIF prev='# AND curr='. AND next='# THEN
RETURN ('#)
ELSEIF prev='# AND curr='# AND next='. THEN
RETURN ('#)
FI
RETURN ('.)
PROC NextGeneration(CHAR ARRAY s)
BYTE i
CHAR prev,curr,next
IF s(0)<4 THEN RETURN FI
prev=s(1) curr=s(2) next=s(3)
i=2
DO
s(i)=CalcCell(prev,curr,next)
i==+1
IF i=s(0) THEN EXIT FI
prev=curr curr=next next=s(i+1)
OD
RETURN
PROC Main()
DEFINE MAXGEN="9"
CHAR ARRAY s=".###.##.#.#.#.#..#.."
BYTE i
FOR i=0 TO MAXGEN
DO
PrintF("Generation %I: %S%E",i,s)
IF i<MAXGEN THEN
NextGeneration(s)
FI
OD
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/One-dimensional_cellular_automata.png Screenshot from Atari 8-bit computer]
<pre>
Generation 0: .###.##.#.#.#.#..#..
Generation 1: .#.#####.#.#.#......
Generation 2: ..##...##.#.#.......
Generation 3: ..##...###.#........
Generation 4: ..##...#.##.........
Generation 5: ..##....###.........
Generation 6: ..##....#.#.........
Generation 7: ..##.....#..........
Generation 8: ..##................
Generation 9: ..##................
</pre>
=={{header|Ada}}==
<
procedure Cellular_Automata is
Line 129 ⟶ 209:
Step (Culture);
end loop;
end Cellular_Automata;</
The implementation defines Petri dish type with Boolean items
Line 154 ⟶ 234:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<
INT universe width = 20;
FORMAT alive or dead = $b("#","_")$;
Line 196 ⟶ 276:
FI;
universe := next universe
OD</
{{out}}
<pre>
Line 216 ⟶ 296:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<
INT upb universe = 20;
FORMAT alive or dead = $b("#","_")$;
Line 250 ⟶ 330:
next universe[UPB universe] := couple(universe[UPB universe - 1: ]);
universe := next universe
OD</
{{out}}
<pre>
Line 267 ⟶ 347:
=={{header|ALGOL W}}==
Using a string to represent the cells and stopping when the next state is th same as the previous one.
<
string(20) state;
string(20) nextState;
Line 286 ⟶ 366:
generation := generation + 1
end while_not_finished
end.</
{{out}}
<pre>
Line 299 ⟶ 379:
Generation 8 __##________________
</pre>
=={{header|Amazing Hopper}}==
<p>Amazing Hopper flavour "BASICO", in spanish.</p>
<p>VERSION 1:</p>
<syntaxhighlight lang="c">
#include <basico.h>
algoritmo
tamaño de pila 65
x = 0
enlistar (0,0,1,1,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,\
1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,0,0,\
1,1,0,0,0,0,0,1,0,1,0,1,1,1,1,1,1,1,0,0) mover a 'x'
x2 = x
decimales '0', token.separador ("")
iterar para ( k=1, #(k<=15), ++k )
imprimir ' #(utf8("Generación #")),k, "\t", x, NL '
iterar para ( j=2, #(j<60), ++j )
#(x2[j] = 0)
cuando ( #( (x[j-1]+x[j]+x[j+1])==2 ) ){
#(x2[j]=1)
}
siguiente
x = x2
siguiente
terminar
</syntaxhighlight>
{{out}}
<pre>
Generación #1 001110011010110111001111110111011111010011000001010111111100
Generación #2 001010011101111101001000011101110001100011000000101100000100
Generación #3 000100010111000110000000010111010001100011000000011100000000
Generación #4 000000001101000110000000001101100001100011000000010100000000
Generación #5 000000001110000110000000001111100001100011000000001000000000
Generación #6 000000001010000110000000001000100001100011000000000000000000
Generación #7 000000000100000110000000000000000001100011000000000000000000
Generación #8 000000000000000110000000000000000001100011000000000000000000
Generación #9 000000000000000110000000000000000001100011000000000000000000
Generación #10 000000000000000110000000000000000001100011000000000000000000
Generación #11 000000000000000110000000000000000001100011000000000000000000
Generación #12 000000000000000110000000000000000001100011000000000000000000
Generación #13 000000000000000110000000000000000001100011000000000000000000
Generación #14 000000000000000110000000000000000001100011000000000000000000
Generación #15 000000000000000110000000000000000001100011000000000000000000
</pre>
<p>VERSION 2:</p>
<syntaxhighlight lang="c">
#include <basico.h>
algoritmo
x={}
'0,0,1,1,1,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0' anidar en lista 'x'
'1,1,1,1,1,1,0,1,1,1,0,1,1,1,1,1,0,1,0,0' anidar en lista 'x'
'1,1,0,0,0,0,0,1,0,1,0,1,1,1,1,1,1,1,0,0' anidar en lista 'x'
x2 = x, k=10
decimales '0', token.separador ("")
iterar
imprimir ' #(utf8("Generación #")), #(11-k), "\t", x, NL '
iterar para ( j=2, #(j<60), ++j )
#( x2[j] = ((x[j-1]+x[j]+x[j+1])==2) )
siguiente
x = x2
mientras ' k-- '
terminar
</syntaxhighlight>
{{out}}
<pre>
Generación #1 001110011010110111001111110111011111010011000001010111111100
Generación #2 001010011101111101001000011101110001100011000000101100000100
Generación #3 000100010111000110000000010111010001100011000000011100000000
Generación #4 000000001101000110000000001101100001100011000000010100000000
Generación #5 000000001110000110000000001111100001100011000000001000000000
Generación #6 000000001010000110000000001000100001100011000000000000000000
Generación #7 000000000100000110000000000000000001100011000000000000000000
Generación #8 000000000000000110000000000000000001100011000000000000000000
Generación #9 000000000000000110000000000000000001100011000000000000000000
Generación #10 000000000000000110000000000000000001100011000000000000000000
Generación #11 000000000000000110000000000000000001100011000000000000000000
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">evolve: function [arr][
ary: [0] ++ arr ++ [0]
ret: new []
loop 1..(size ary)-2 'i [
a: ary\[i-1]
b: ary\[i]
c: ary\[i+1]
if? 2 = a+b+c -> 'ret ++ 1
else -> 'ret ++ 0
]
ret
]
printIt: function [arr][
print replace replace join map arr 'n -> to :string n "0" "_" "1" "#"
]
arr: [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]
printIt arr
newGen: evolve arr
while [newGen <> arr][
arr: newGen
newGen: evolve arr
printIt newGen
]</syntaxhighlight>
{{out}}
<pre>_###_##_#_#_#_#__#__
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________</pre>
=={{header|AutoHotkey}}==
ahk [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=147 discussion]
<
Loop % n { ; draw a line of checkboxes
Line 324 ⟶ 528:
GuiClose: ; exit when GUI is closed
ExitApp</
=={{header|AWK}}==
<
BEGIN {
edge = 1
Line 397 ⟶ 601:
}
}
</syntaxhighlight>
{{out}}
Line 413 ⟶ 617:
</pre>
<
cat automata.awk :
Line 456 ⟶ 660:
} while (str_ != str_previous)
}
</syntaxhighlight>
{{out}}
Line 474 ⟶ 678:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|Locomotive BASIC}}
<syntaxhighlight lang="qbasic">100 HOME
110 n = 10
120 READ w : DIM x(w+1),x2(w+1) : FOR i = 1 TO w : READ x(i) : NEXT
130 FOR k = 1 TO n
140 FOR j = 1 TO w
150 IF x(j) THEN PRINT "#";
155 IF NOT x(j) THEN PRINT "_";
160 IF x(j-1)+x(j)+x(j+1) = 2 THEN x2(j) = 1
165 IF x(j-1)+x(j)+x(j+1) <> 2 THEN x2(j) = 0
170 NEXT : PRINT
180 FOR j = 1 TO w : x(j) = x2(j) : NEXT
190 NEXT
200 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0</syntaxhighlight>
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">arraybase 1
dim start = {0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0}
dim sgtes(start[?]+1)
for k = 0 to 9
print "Generation "; k; ": ";
for j = 0 to start[?]-1
if start[j] then print "#"; else print "_";
if start[j-1] + start[j] + start[j+1] = 2 then sgtes[j] = 1 else sgtes[j] = 0
next j
print
for j = 0 to start[?]-1
start[j] = sgtes[j]
next j
next k</syntaxhighlight>
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> DIM rule$(7)
rule$() = "0", "0", "0", "1", "0", "1", "1", "0"
now$ = "01110110101010100100"
FOR generation% = 0 TO 9
PRINT "Generation " ; generation% ":", now$
next$ = ""
FOR cell% = 1 TO LEN(now$)
next$ += rule$(EVAL("%"+MID$("0"+now$+"0", cell%, 3)))
NEXT cell%
SWAP now$, next$
NEXT generation%</syntaxhighlight>
{{out}}
<pre>Generation 0: 01110110101010100100
Generation 1: 01011111010101000000
Generation 2: 00110001101010000000
Generation 3: 00110001110100000000
Generation 4: 00110001011000000000
Generation 5: 00110000111000000000
Generation 6: 00110000101000000000
Generation 7: 00110000010000000000
Generation 8: 00110000000000000000
Generation 9: 00110000000000000000</pre>
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
{{works with|BASICA}}
{{works with|GW-BASIC}}
{{works with|MSX BASIC}}
{{works with|PC-BASIC|any}}
{{works with|QBasic}}
{{works with|QuickBasic}}
{{works with|Quite BASIC}}
<syntaxhighlight lang="qbasic">100 CLS
110 LET n = 10
120 READ w
121 DIM x(w+1): DIM x2(w+1)
122 FOR i = 1 TO w : READ x(i) : NEXT i
130 FOR k = 1 TO n
140 FOR j = 1 TO w
150 IF x(j) THEN PRINT "#"; ELSE PRINT "_";
160 IF x(j-1)+x(j)+x(j+1) = 2 THEN LET x2(j) = 1 ELSE LET x2(j) = 0
170 NEXT j
171 PRINT
180 FOR j = 1 TO w : LET x(j) = x2(j) : NEXT j
190 NEXT k
200 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0
210 END</syntaxhighlight>
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">#define SIZE 640
randomize timer
dim as ubyte arr(0 to SIZE-1, 0 to 1)
dim as uinteger i
for i = 0 to SIZE - 1 'initialise array with zeroes and ones
arr(i, 0)=int(rnd+0.5)
next i
screen 12 'display graphically
dim as string ch=" "
dim as uinteger j = 0, cur = 0, nxt, prv, neigh
while not ch = "q" or ch = "Q"
for i = 0 to SIZE - 1
pset(i, j), 8+7*arr(i,cur) 'print off cells as grey, on cells as bright white
nxt = (i + 1) mod SIZE
prv = (i - 1)
if prv < 0 then prv = SIZE - 1 'let's have a wrap-around array for fun
neigh = arr(prv, cur) + arr(nxt, cur)
if arr(i, cur) = 0 then 'evolution rules
if neigh = 2 then
arr(i, 1-cur) = 1
else
arr(i, 1-cur) = 0
end if
else
if neigh = 0 or neigh = 2 then
arr(i, 1-cur) = 0
else
arr(i, 1-cur) = 1
end if
end if
next i
j = j + 1
cur = 1 - cur
do
ch = inkey
if ch <> "" then exit do 'press any key to advance the sim
'or Q to exit
loop
wend</syntaxhighlight>
==={{header|GFA Basic}}===
<syntaxhighlight lang="text">
'
' One Dimensional Cellular Automaton
'
start$="01110110101010100100"
max_cycles%=20 ! give a maximum depth
'
' Global variables hold the world, with two rows
' world! is set up with 2 extra cells width, so there is a FALSE on either side
' cur% gives the row for current world,
' new% gives the row for the next world.
'
size%=LEN(start$)
DIM world!(size%+2,2)
cur%=0
new%=1
clock%=0
'
@setup_world(start$)
OPENW 1
CLEARW 1
DO
@display_world
@update_world
EXIT IF @same_state
clock%=clock%+1
EXIT IF clock%>max_cycles% ! safety net
LOOP
~INP(2)
CLOSEW 1
'
' parse given string to set up initial states in world
' -- assumes world! is of correct size
'
PROCEDURE setup_world(defn$)
LOCAL i%
' clear out the array
ARRAYFILL world!(),FALSE
' for each 1 in string, set cell to true
FOR i%=1 TO LEN(defn$)
IF MID$(defn$,i%,1)="1"
world!(i%,0)=TRUE
ENDIF
NEXT i%
' set references to cur and new
cur%=0
new%=1
RETURN
'
' Display the world
'
PROCEDURE display_world
LOCAL i%
FOR i%=1 TO size%
IF world!(i%,cur%)
PRINT "#";
ELSE
PRINT ".";
ENDIF
NEXT i%
PRINT ""
RETURN
'
' Create new version of world
'
PROCEDURE update_world
LOCAL i%
FOR i%=1 TO size%
world!(i%,new%)=@new_state(@get_value(i%))
NEXT i%
' reverse cur/new
cur%=1-cur%
new%=1-new%
RETURN
'
' Test if cur/new states are the same
'
FUNCTION same_state
LOCAL i%
FOR i%=1 TO size%
IF world!(i%,cur%)<>world!(i%,new%)
RETURN FALSE
ENDIF
NEXT i%
RETURN TRUE
ENDFUNC
'
' Return new state of cell given value
'
FUNCTION new_state(value%)
SELECT value%
CASE 0,1,2,4,7
RETURN FALSE
CASE 3,5,6
RETURN TRUE
ENDSELECT
ENDFUNC
'
' Compute value for cell + neighbours
'
FUNCTION get_value(cell%)
LOCAL result%
result%=0
IF world!(cell%-1,cur%)
result%=result%+4
ENDIF
IF world!(cell%,cur%)
result%=result%+2
ENDIF
IF world!(cell%+1,cur%)
result%=result%+1
ENDIF
RETURN result%
ENDFUNC</syntaxhighlight>
==={{header|GW-BASIC}}===
The [[#Chipmunk Basic|Chipmunk Basic]] solution works without any changes.
==={{header|Liberty BASIC}}===
{{works with|Just BASIC}}
{{works with|Run BASIC}}
<syntaxhighlight lang="lb">' [RC] 'One-dimensional cellular automata'
' does not wrap so fails for some rules
rule$ ="00010110" ' Rule 22 decimal
state$ ="0011101101010101001000"
for j =1 to 20
print state$
oldState$ =state$
state$ ="0"
for k =2 to len( oldState$) -1
NHood$ =mid$( oldState$, k -1, 3) ' pick 3 char neighbourhood and turn binary string to decimal
vNHood =0
for kk =3 to 1 step -1
vNHood =vNHood +val( mid$( NHood$, kk, 1)) *2^( 3 -kk)
next kk
' .... & use it to index into rule$ to find appropriate new value
state$ =state$ +mid$( rule$, vNHood +1, 1)
next k
state$ =state$ +"0"
next j
end</syntaxhighlight>
==={{header|Locomotive Basic}}===
<syntaxhighlight lang="locobasic">10 MODE 1:n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT
20 FOR k=1 TO n
30 FOR j=1 TO w
40 IF x(j) THEN PRINT "#"; ELSE PRINT "_";
50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0
60 NEXT:PRINT
70 FOR j=1 TO w:x(j)=x2(j):NEXT
80 NEXT
90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0</syntaxhighlight>
{{out}}
[[File:Cellular automaton locomotive basic.png]]
==={{header|MSX Basic}}===
The [[#Chipmunk Basic|Chipmunk Basic]] solution works without any changes.
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">EnableExplicit
Dim cG.i(21)
Dim nG.i(21)
Define.i n, Gen
DataSection
Data.i 0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0
EndDataSection
For n=1 To 20
Read.i cG(n)
Next
OpenConsole()
Repeat
Print("Generation "+Str(Gen)+": ")
For n=1 To 20
Print(Chr(95-cG(n)*60))
Next
Gen +1
PrintN("")
For n=1 To 20
If (cG(n) And (cG(n-1) XOr cg(n+1))) Or (Not cG(n) And (cG(n-1) And cg(n+1)))
nG(n)=1
Else
nG(n)=0
EndIf
Next
CopyArray(nG(), cG())
Until Gen > 9
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</syntaxhighlight>
{{out}}
<pre>Generation 0: _###_##_#_#_#_#__#__
Generation 1: _#_#####_#_#_#______
Generation 2: __##___##_#_#_______
Generation 3: __##___###_#________
Generation 4: __##___#_##_________
Generation 5: __##____###_________
Generation 6: __##____#_#_________
Generation 7: __##_____#__________
Generation 8: __##________________
Generation 9: __##________________</pre>
==={{header|QBasic}}===
{{works with|QBasic|1.1}}
{{works with|QuickBasic|4.5}}
{{trans|Java}}
<
DECLARE FUNCTION getNeighbors! (group$)
CLS
Line 528 ⟶ 1,073:
NEXT i
life$ = newGen$
END FUNCTION</
{{out}}
<pre>Generation 0 : _###_##_#_#_#_#__#__
Line 541 ⟶ 1,086:
Generation 9 : __##________________</pre>
==={{header|
The [[#Chipmunk Basic|Chipmunk Basic]] solution works without any changes.
==={{header|Run BASIC}}===
The [[#Liberty BASIC|Liberty BASIC]] solution works without any changes.
==={{header|Sinclair ZX81 BASIC}}===
Works with the unexpanded (1k RAM) ZX81.
<
20 LET G=1
30 PRINT N$
Line 606 ⟶ 1,112:
170 NEXT I
180 LET G=G+1
190 IF N$<>O$ THEN GOTO 40</
{{out}}
The program overwrites each cell on the screen as it updates it (which it does quite slowly—there is no difficulty about watching what it is doing), with a counter to the right showing the generation it is currently working on. When it is part of the way through, for example, the display looks like this:
Line 612 ⟶ 1,118:
It halts when a stable state has been reached:
<pre>00110000000000000000 9</pre>
==={{header|Visual Basic .NET}}===
This implementation is run from the command line. The command is followed by a string of either 1's or #'s for an active cell, or 0's or _'s for an inactive one.
<syntaxhighlight lang="visual basic .net">Imports System.Text
Module CellularAutomata
Private Enum PetriStatus
Active
Stable
Dead
End Enum
Function Main(ByVal cmdArgs() As String) As Integer
If cmdArgs.Length = 0 Or cmdArgs.Length > 1 Then
Console.WriteLine("Command requires string of either 1s and 0s or #s and _s.")
Return 1
End If
Dim petriDish As BitArray
Try
petriDish = InitialisePetriDish(cmdArgs(0))
Catch ex As Exception
Console.WriteLine(ex.Message)
Return 1
End Try
Dim generation As Integer = 0
Dim ps As PetriStatus = PetriStatus.Active
Do While True
If ps = PetriStatus.Stable Then
Console.WriteLine("Sample stable after {0} generations.", generation - 1)
Exit Do
Else
Console.WriteLine("{0}: {1}", generation.ToString("D3"), BuildDishString(petriDish))
If ps = PetriStatus.Dead Then
Console.WriteLine("Sample dead after {0} generations.", generation)
Exit Do
End If
End If
ps = GetNextGeneration(petriDish)
generation += 1
Loop
Return 0
End Function
Private Function InitialisePetriDish(ByVal Sample As String) As BitArray
Dim PetriDish As New BitArray(Sample.Length)
Dim dead As Boolean = True
For i As Integer = 0 To Sample.Length - 1
Select Case Sample.Substring(i, 1)
Case "1", "#"
PetriDish(i) = True
dead = False
Case "0", "_"
PetriDish(i) = False
Case Else
Throw New Exception("Illegal value in string position " & i)
Return Nothing
End Select
Next
If dead Then
Throw New Exception("Entered sample is dead.")
Return Nothing
End If
Return PetriDish
End Function
Private Function GetNextGeneration(ByRef PetriDish As BitArray) As PetriStatus
Dim petriCache = New BitArray(PetriDish.Length)
Dim neighbours As Integer
Dim stable As Boolean = True
Dim dead As Boolean = True
For i As Integer = 0 To PetriDish.Length - 1
neighbours = 0
If i > 0 AndAlso PetriDish(i - 1) Then neighbours += 1
If i < PetriDish.Length - 1 AndAlso PetriDish(i + 1) Then neighbours += 1
petriCache(i) = (PetriDish(i) And neighbours = 1) OrElse (Not PetriDish(i) And neighbours = 2)
If PetriDish(i) <> petriCache(i) Then stable = False
If petriCache(i) Then dead = False
Next
PetriDish = petriCache
If dead Then Return PetriStatus.Dead
If stable Then Return PetriStatus.Stable
Return PetriStatus.Active
End Function
Private Function BuildDishString(ByVal PetriDish As BitArray) As String
Dim sw As New StringBuilder()
For Each b As Boolean In PetriDish
sw.Append(IIf(b, "#", "_"))
Next
Return sw.ToString()
End Function
End Module</syntaxhighlight>
Output:
<pre>C:\>CellularAutomata _###_##_#_#_#_#__#__
000: _###_##_#_#_#_#__#__
001: _#_#####_#_#_#______
002: __##___##_#_#_______
003: __##___###_#________
004: __##___#_##_________
005: __##____###_________
006: __##____#_#_________
007: __##_____#__________
008: __##________________
Sample stable after 8 generations.</pre>
==={{header|Yabasic}}===
{{trans|Locomotive_Basic}}
<syntaxhighlight lang="yabasic">10 n=10:READ w:DIM x(w+1),x2(w+1):FOR i=1 to w:READ x(i):NEXT
20 FOR k=1 TO n
30 FOR j=1 TO w
40 IF x(j) THEN PRINT "#"; ELSE PRINT "_"; END IF
50 IF x(j-1)+x(j)+x(j+1)=2 THEN x2(j)=1 ELSE x2(j)=0 END IF
60 NEXT:PRINT
70 FOR j=1 TO w:x(j)=x2(j):NEXT
80 NEXT
90 DATA 20,0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0</syntaxhighlight>
Other solution
<syntaxhighlight lang="yabasic">start$ = "0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0"
dim x$(1)
for k = 1 to 10
n = token(start$, x$(), ",")
redim x$(n+1)
start$ = ""
for j = 1 to n
if val(x$(j)) then print "#"; else print "_"; end if
test = abs(val(x$(j-1)) + val(x$(j)) + val(x$(j+1)) = 2)
start$ = start$ + str$(test) + ","
next j
print
next k</syntaxhighlight>
=={{header|Batch File}}==
This implementation will not stop showing generations, unless the cellular automata is already stable.
<
setlocal enabledelayedexpansion
Line 672 ⟶ 1,329:
set proc=%newgen%
goto :nextgen
::/THE (LLLLLLOOOOOOOOOOOOONNNNNNNNGGGGGG.....) PROCESSOR</
{{out}}
<pre> | __###__##_#_##_###__######_###_#####_#__##_____#_#_#######__ |
Line 684 ⟶ 1,341:
...The sample is now stable.</pre>
=={{header|Befunge}}==
<
" !!! !! ! ! ! ! ! " ,*25 <v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
Line 727 ⟶ 1,358:
^ >$$$$320p10g1+:9`v > >$"!"> 20g10g1+p 20g1+:20p
^ v_10p10g
> ^</
=={{header|Bracmat}}==
<
= n z
. @( !arg
Line 759 ⟶ 1,390:
& evolve$!S:?S
)
);</
{{out}}
<pre>11101101010101001001
Line 772 ⟶ 1,403:
=={{header|C}}==
<
#include <string.h>
Line 799 ⟶ 1,430:
do { printf(c + 1); } while (evolve(c + 1, b + 1, sizeof(c) - 3));
return 0;
}</
{{out}}
<pre>###_##_#_#_#_#__#__
Line 812 ⟶ 1,443:
Similar to above, but without a backup string:
<
char trans[] = "___#_##_";
Line 838 ⟶ 1,469:
do { printf(c + 1); } while (evolve(c + 1, sizeof(c) - 3));
return 0;
}</
=={{header|C sharp}}==
<
using System.Collections.Generic;
Line 879 ⟶ 1,510:
}
}
}</
=={{header|C++}}==
Uses std::bitset for efficient packing of bit values.
<
#include <bitset>
#include <string>
Line 911 ⟶ 1,542:
std::cout << std::endl;
}
}</
{{out}}
Line 926 ⟶ 1,557:
=={{header|Ceylon}}==
<
shared Character character;
string => character.string;
Line 991 ⟶ 1,622:
print("generation `` ++generation `` ``automata``");
}
}</
=={{header|Clojure}}==
<
(:require (clojure.contrib (string :as s))))
Line 1,009 ⟶ 1,640:
'()
(cons cells (generate (dec n) (next-gen cells)))))
</syntaxhighlight>
<
(println cells))
_###_##_#_#_#_#__#__
Line 1,022 ⟶ 1,653:
__##________________
nil
</syntaxhighlight>
Another way:
<
(require '[clojure.string :as str])
Line 1,050 ⟶ 1,681:
(do (println g)
(recur (compute-next-genr g)
(inc i)))))</
Yet another way, easier to understand
<
(def rules
{
Line 1,078 ⟶ 1,709:
(doseq [g (take 10 (iterate nextgen [0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0]))]
(println g))
</syntaxhighlight>
=={{header|COBOL}}==
<
Identification division.
Program-id. rc-1d-cell.
Line 1,191 ⟶ 1,822:
end-perform
.
</syntaxhighlight>
{{out}}
Line 1,215 ⟶ 1,846:
_##_____#__________
_##________________={{header|CoffeeScript}}==
<
# We could cheat and count the bits, but let's keep this general.
# . = dead, # = alive, middle cells survives iff one of the configurations
Line 1,248 ⟶ 1,879:
simulate (c == '#' for c in ".###.##.#.#.#.#..#..")
</syntaxhighlight>
{{out}}
<pre>
Line 1,263 ⟶ 1,894:
equilibrium achieved
</pre>
=={{header|Common Lisp}}==
Based upon the Ruby version.
<
(assert (> (length x) 1))
(coerce x 'simple-bit-vector))
Line 1,293 ⟶ 1,926:
do (princ (if (zerop (bit value i)) #\. #\#)
stream))
(terpri stream))</
<
for value = #*01110110101010100100 then (next-cycle value)
until (equalp value previous-value)
Line 1,307 ⟶ 1,940:
..##....#.#.........
..##.....#..........
..##................</
=={{header|D}}==
<
import std.stdio, std.algorithm;
Line 1,328 ⟶ 1,961:
writeln;
}
}</
{{out}}
<pre>__###_##_#_#_#_#__#___
Line 1,343 ⟶ 1,976:
===Alternative Version===
{{trans|Raku}}
<
import std.stdio, std.algorithm, std.range;
Line 1,355 ⟶ 1,988:
A.swap(B);
} while (A != B);
}</
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 1,370 ⟶ 2,003:
This version saves memory representing the state in an array of bits. For a higher performance a SWAR approach should be tried.
{{trans|C++}}
<
import std.stdio, std.algorithm, std.range, std.bitmanip;
Line 1,393 ⟶ 2,026:
A.swap(B);
}
}</
The output is the same as the second version.
=={{header|DWScript}}==
<
const table = [0, 0, 0, 1, 0, 1, 1, 0];
Line 1,417 ⟶ 2,050:
PrintLn('');
end;
</syntaxhighlight>
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 1,432 ⟶ 2,065:
=={{header|Déjà Vu}}==
<
0 ]
repeat size:
Line 1,467 ⟶ 2,100:
return print-state drop
run 60</
{{out}}
<pre>001110011010110111001111110111011111010011000001010111111100
Line 1,478 ⟶ 2,111:
000000000000000110000000000000000001100011000000000000000000
000000000000000110000000000000000001100011000000000000000000</pre>
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
<syntaxhighlight lang="Delphi">
type TGame = string[20];
type TPattern = string[3];
function GetSubPattern(Game: TGame; Inx: integer): TPattern;
{Get the pattern of three cells adjacent to Inx}
var I: integer;
begin
Result:='';
{Cells off the ends of the array are consider empty}
for I:=Inx-1 to Inx+1 do
if (I<1) or (I>Length(Game)) then Result:=Result+' '
else Result:=Result+Game[I];
end;
function GetNewValue(P: TPattern): char;
{Calculate the new value for a cell based}
{the pattern of neighboring cells}
begin
if P=' ' then Result:=' ' { No change}
else if P=' #' then Result:=' ' { No change}
else if P=' # ' then Result:=' ' { Dies without enough neighbours}
else if P=' ##' then Result:='#' { Needs one neighbour to survive}
else if P='# ' then Result:=' ' { No change}
else if P='# #' then Result:='#' { Two neighbours giving birth}
else if P='## ' then Result:='#' { Needs one neighbour to survive}
else if P='###' then Result:=' '; { Starved to death.}
end;
procedure CellularlAutoGame(Memo: TMemo);
{Iterate through steps of evolution of cellular automaton}
var GameArray,NextArray: TGame;
var P: string [3];
var I,G: integer;
begin
{Start arrangement}
GameArray:=' ### ## # # # # # ';
for G:=1 to 10 do
begin
{Display current game situation}
Memo.Lines.Add(GameArray);
{Evolve each cell in the array}
for I:=1 to Length(GameArray) do
begin
P:=GetSubPattern(GameArray,I);
NextArray[I]:=GetNewValue(P);
end;
GameArray:=NextArray;
end;
end;
</syntaxhighlight>
{{out}}
<pre>
### ## # # # # #
# ##### # # #
## ## # #
## ### #
## # ##
## ###
## # #
## #
##
##
Elapsed Time: 9.784 ms.
</pre>
=={{header|E}}==
<
var result := state(0, 1) # fixed left cell
for i in 1..(state.size() - 2) {
Line 1,498 ⟶ 2,206:
}
return state
}</
<
" " => " ",
" #" => " ",
Line 1,522 ⟶ 2,230:
8 | ##
9 | ##
# value: " ## "</
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
map[] = [ 0 0 0 1 0 1 1 0 ]
cell[] = [ 0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0 ]
len celln[] len cell[]
proc evolve . .
for i = 2 to len cell[] - 1
ind = cell[i - 1] + 2 * cell[i] + 4 * cell[i + 1] + 1
celln[i] = map[ind]
.
swap celln[] cell[]
.
proc show . .
for v in cell[]
if v = 1
write "#"
else
write "."
.
.
print ""
.
show
for i to 9
evolve
show
.
</syntaxhighlight>
{{out}}
<pre>
.###.##.#.#.#.#..#..
.#.#####.#.#.#......
..##...##.#.#.......
..##...###.#........
..##...#.##.........
..##....###.........
..##....#.#.........
..##.....#..........
..##................
..##................
</pre>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,598 ⟶ 2,348:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,615 ⟶ 2,365:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def run(list, gen \\ 0) do
print(list, gen)
Line 1,635 ⟶ 2,385:
end
RC.run([0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0])</
{{out}}
Line 1,652 ⟶ 2,402:
=={{header|Elm}}==
<
import List exposing (length, tail, reverse, concat, head, append, map3)
import Html exposing (Html, div, h1, text)
Line 1,741 ⟶ 2,491:
, update = update
, subscriptions = subscriptions
}</
Link to live demo: https://dc25.github.io/oneDimensionalCellularAutomataElm/
=={{header|Erlang}}==
<
-module(ca).
-compile(export_all).
Line 1,795 ⟶ 2,545:
next([1,1,1|T],Acc) ->
next([1,1|T],[0|Acc]).
</syntaxhighlight>
Example execution:
<
44> ca:run(9,[0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0]).
0: __###_##_#_#_#_#__#___
Line 1,809 ⟶ 2,559:
8: ___##_________________
9: ___##_________________
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM ONEDIM_AUTOMATA
Line 1,846 ⟶ 2,596:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 1,872 ⟶ 2,622:
=={{header|Euphoria}}==
<
function rules(integer tri)
Line 1,917 ⟶ 2,667:
printf(1,"Generation %d: ",n)
print_gen(gen)</
{{out}}
Line 1,931 ⟶ 2,681:
=={{header|Factor}}==
<
IN: cellular
Line 1,952 ⟶ 2,702:
10 [ dup print-cellular step ] times print-cellular ;
MAIN: main-cellular
</syntaxhighlight>
<pre>( scratchpad ) "cellular" run
_###_##_#_#_#_#__#__
Line 1,967 ⟶ 2,717:
=={{header|Fantom}}==
<
class Automaton
{
Line 1,998 ⟶ 2,748:
}
}
</syntaxhighlight>
=={{header|FOCAL}}==
<syntaxhighlight lang="focal">1.1 S OLD(2)=1; S OLD(3)=1; S OLD(4)=1; S OLD(6)=1; S OLD(7)=1
1.2 S OLD(9)=1; S OLD(11)=1; S OLD(13)=1; S OLD(15)=1; S OLD(18)=1
1.3 F N=1,10; D 2
1.4 Q
2.1 F X=1,20; D 3
2.2 F X=1,20; D 6
2.3 F X=1,20; S OLD(X)=NEW(X)
2.4 T !
3.1 I (OLD(X-1)+OLD(X)+OLD(X+1)-2)4.1,5.1,4.1
4.1 S NEW(X)=0
5.1 S NEW(X)=1
6.1 I (-OLD(X))7.1,8.1,8.1
7.1 T "#"
8.1 T "."</syntaxhighlight>
{{output}}
<pre>
.###.##.#.#.#.#..#..
.#.#####.#.#.#......
..##...##.#.#.......
..##...###.#........
..##...#.##.........
..##....###.........
..##....#.#.........
..##.....#..........
..##................
..##................
</pre>
=={{header|Forth}}==
<
0 do dup 1 and c, 2/ loop drop ;
Line 2,025 ⟶ 2,811:
.state 1 do gen .state loop ;
10 life1d</
ouput
<syntaxhighlight lang="text">
### ## # # # # #
# ##### # # #
Line 2,039 ⟶ 2,825:
##
## ok
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
IMPLICIT NONE
Line 2,092 ⟶ 2,878:
END SUBROUTINE Drawgen
END PROGRAM LIFE_1D</
{{out}}
<pre>
Line 2,105 ⟶ 2,891:
Generation 8: __##________________
Generation 9: __##________________</pre>
=={{header|Go}}==
===Sequential===
<
import "fmt"
Line 2,263 ⟶ 2,931:
return g0[1:last]
}
}</
{{out}}
<pre>
Line 2,283 ⟶ 2,951:
Separate read and write phases.
Single array of cells.
<
import (
Line 2,337 ⟶ 3,005:
write.Wait()
}
}</
Output is same as sequential version.
=={{header|Groovy}}==
Solution:
<
def right = self[1..-1] + [false]
def left = [false] + self[0..-2]
[left, self, right].transpose().collect { hood -> hood.count { it } == 2 }
}</
Test:
<
println "Generation 0: ${cells.collect { g -> g ? '#' : '_' }.join()}"
(1..9).each {
cells = life1D(cells)
println "Generation ${it}: ${cells.collect { g -> g ? '#' : '_' }.join()}"
}</
{{out}}
Line 2,369 ⟶ 3,037:
=={{header|Haskell}}==
<syntaxhighlight lang
import
bnd :: String -> Char
Line 2,376 ⟶ 3,044:
bnd "#_#" = '#'
bnd "##_" = '#'
bnd
nxt :: String -> String
Line 2,386 ⟶ 3,054:
lahmahgaan :: String -> [String]
lahmahgaan xs =
init
((==) . last <*> last . init)
((<>) <*> pure . nxt . last)
$ [xs, nxt xs]
main :: IO ()
main =
>>= ( mapM_ putStrLn . lahmahgaan
. map ("_#" !!)
. take 36
. randomRs (0, 1)
)</syntaxhighlight>
{{Out}}
For example:
_#_##______#_#_#####_#_____###____##
___#_________#_#___##_____________##
______________#____##_____________##
___________________##_____________##</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
# One dimensional Cellular automaton
record Automaton(size, cells)
Line 2,454 ⟶ 3,118:
}
end
</syntaxhighlight>
An alternative approach is to represent the automaton as a string.
Line 2,465 ⟶ 3,129:
the evolve procedure fails if a new generation is unchanged from the previous, stopping the generation cycle early.
<
A := if *A = 0 then ["01110110101010100100"]
CA := show("0"||A[1]||"0") # add always dead border cells
Line 2,480 ⟶ 3,144:
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</
{{out|A couple of sample runs}}
Line 2,499 ⟶ 3,163:
00110000
-></pre>
=={{Header|Insitux}}==
<syntaxhighlight lang="insitux">
(function next cells
(... str
(map (comp str (count ["#"]) (= 2) #(% "#" "_"))
(str "_" cells)
cells
(str (skip 1 cells) "_"))))
(function generate n cells
(join "\n" (reductions next cells (range n))))
</syntaxhighlight>
{{out}}
Invoking <code>(generate 9 "_###_##_#_#_#_#__#__")</code>
<pre>
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________
</pre>
=={{header|J}}==
<
{{out|Example use}}
<
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
Line 2,513 ⟶ 3,208:
__##____#_#_________
__##_____#__________
__##________________</
Alternative implementation:
<
'_#'{~ (3 ((|.n#:~8#2) {~ #.)\ 0,],0:)^:(i.m)
)</
{{out|Example use}}
<
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
Line 2,531 ⟶ 3,226:
__##____#_#_________
__##_____#__________
__##________________</
=={{header|Java}}==
This example requires a starting generation of at least length two
(which is what you need for anything interesting anyway).
<
public static void main(String[] args) throws Exception{
String start= "_###_##_#_#_#_#__#__";
Line 2,577 ⟶ 3,272:
return ans;
}
}</
{{out}}
<pre>Generation 0: _###_##_#_#_#_#__#__
Line 2,593 ⟶ 3,288:
which is local to the <code>evolve</code> method,
and the <code>evolve</code> method returns a boolean.
<
private static char[] trans = "___#_##_".toCharArray();
Line 2,623 ⟶ 3,318:
}while(evolve(c));
}
}</
{{out}}
<pre>###_##_#_#_#_#__#__
Line 2,642 ⟶ 3,337:
state[i-1] refers to the new cell in question,
(old[i] == 1) checks if the old cell was alive.
<
var old = [0].concat(old, [0]); // Surround with dead cells.
var state = []; // The new state.
Line 2,654 ⟶ 3,349:
}
return state;
}</
{{out|Example usage}}
<
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|jq}}==
The main point of interest in the following is perhaps the way the built-in function "recurse" is used to continue the simulation until quiescence.
<
def next:
# Conveniently, jq treats null as 0 when it comes to addition
Line 2,683 ⟶ 3,378:
# Example:
[0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0] | go</
{{out}}
<
*** ** * * * * *
* ***** * * *
Line 2,694 ⟶ 3,389:
** * *
** *
**</
=={{header|Julia}}==
=== Julia: Implementation as a function accepting a Vector of Bool ===
<syntaxhighlight lang="julia">
automaton(g::Vector{Bool}) =
println(join(alive ? '#' : '_' for alive ∈ g))
end
automaton([c == '#' for c ∈ "_###_##_#_#_#_#__#__"])
</syntaxhighlight>
=== Julia: Implementation as an iterable struct ===
<syntaxhighlight lang="julia">
struct Automaton g₀::Vector{Bool} end
Base.iterate(a::Automaton, g = a.g₀) =
Base.show(io::IO, a::Automaton) = for g in Iterators.take(a, 10)
println(io, join(alive ? '#' : '_' for alive ∈ g)) end
Automaton([c == '#' for c ∈ "_###_##_#_#_#_#__#__"])
</syntaxhighlight>
{{out}}
<pre>
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________
</pre>
=={{header|K}}==
<
{{out|Example usage}}
<
_XXX_XX_X_X_X_X__X__
_X_XXXXX_X_X_X______
Line 2,770 ⟶ 3,442:
__XX_____X__________
__XX________________
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|C}}
<
val trans = "___#_##_"
Line 2,800 ⟶ 3,472:
}
while (evolve(c,b))
}</
{{out}}
Line 2,814 ⟶ 3,486:
_##________________
</pre>
=={{header|Logo}}==
{{works with|UCB Logo}}
<
make "generations 9
Line 2,896 ⟶ 3,526:
end
CA_1D :cell_list :generations</
{{out}}
<pre>
Line 2,912 ⟶ 3,542:
=={{header|Lua}}==
<
f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 }
Line 2,943 ⟶ 3,573:
Output( f, l )
end </
{{out}}
<pre>0: _###_##_#_#_#_#__#__
Line 2,957 ⟶ 3,587:
=={{header|M4}}==
<
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
Line 2,992 ⟶ 3,622:
for(`j',1,10,
`show(x)`'evolve(`x',`y')`'swap(`x',x,`y')
')`'show(x)</
{{out}}
Line 3,011 ⟶ 3,641:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function:
<
Print @@@ (% /. {1 -> "#", 0 -> "."});</
For succinctness, an integral rule can be used:
<
{{out}}
<
#.#####.#.#.#....
.##...##.#.#.....
Line 3,028 ⟶ 3,658:
.##..............
.##..............
.##..............</
=={{header|MATLAB}} / {{header|Octave}}==
<
V='_#';
while n>=0;
Line 3,039 ⟶ 3,669:
v = v(3:end)==2;
end;
end</
{{out}}
<pre>octave:27> one_dim_cell_automata('01110110101010100100'=='1',20);
Line 3,061 ⟶ 3,691:
but it segfaults when trying to use <code>BOOLEAN</code> types,
so we use <code>INTEGER</code> instead.
<
IMPORT IO, Fmt, Word;
Line 3,103 ⟶ 3,733:
Step(culture);
END;
END Cell.</
{{out}}
<pre>
Line 3,119 ⟶ 3,749:
=={{header|MontiLang}}==
<
35 VAR height .
FOR length 0 ENDFOR 1 0 ARR VAR list .
Line 3,197 ⟶ 3,827:
next printArr .
next 0 ADD APPEND . VAR list .
ENDFOR</
=={{header|Nial}}==
(life.nial)
<
wi is rest link [write, pass]
% calculate the neighbors by rotating the array left and right and joining them
Line 3,210 ⟶ 3,840:
nextgen is each igen neighbors
% 42
life is fork [ > [sum pass, 0 first], life nextgen wi, pass ]</
{{out|Using it}}
<
|I := [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]
|life I</
=={{header|Nim}}==
<
Line 3,265 ⟶ 3,895:
if map2 == map: break
map = map2</
{{out}}
<pre>_###_##_#_#_#_#__#____________
Line 3,279 ⟶ 3,909:
'''Using a string character counting method''':
<
const
Line 3,306 ⟶ 3,936:
q0 = q1
q1 = evolve(q0)
echo(q1)</
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 3,320 ⟶ 3,950:
'''Using nested functions and method calling style:'''
<
proc evolveInto(x, t : var string) =
for i in x.low..x.high:
Line 3,340 ⟶ 3,970:
swap t, x
cellAutomata()</syntaxhighlight>
{{out}}
Line 3,357 ⟶ 3,986:
=={{header|OCaml}}==
<
try g.(i)
with _ -> 0
Line 3,385 ⟶ 4,014:
else print_char '#'
done;
print_newline()</
put the code above in a file named "life.ml",
Line 3,421 ⟶ 4,050:
=={{header|Oforth}}==
<
| i s |
l byteSize dup ->s String newSize
Line 3,433 ⟶ 4,062:
: gen( l n -- )
l dup .cr #[ nextGen dup .cr ] times( n ) drop ;</
{{out}}
Line 3,453 ⟶ 4,082:
=={{header|Oz}}==
<
A0 = {List.toTuple unit "_###_##_#_#_#_#__#__"}
Line 3,488 ⟶ 4,117:
do
{System.showInfo "Gen. "#I#": "#{Record.toList A}}
end</
{{out}}
Line 3,508 ⟶ 4,137:
This function generates one generation from a previous one,
passed as a 0-1 vector.
<
To simulate a run of 10 generations of the automaton, the function above can be put in a loop that spawns a new generation as a function of nth generations passed (n=0 is the initial state):
<
=== Output ===
<syntaxhighlight lang="text">
[0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0]
[0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0]
Line 3,526 ⟶ 4,155:
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
</syntaxhighlight>
=={{header|Pascal}}==
<
{$IFDEF FPC}{$MODE DELPHI}{$ELSE}{$APPTYPE}{$ENDIF}
uses
Line 3,601 ⟶ 4,230:
NextRow(@row[0],High(row));
end;
end.</
{{Out}}<pre>
__###_##_#_#_#_#__#__
Line 3,619 ⟶ 4,248:
Convert cells to zeros and ones to set complement state
<
$_="_###_##_#_#_#_#__#__\n";
do {
Line 3,627 ⟶ 4,256:
s/(?<=(.))(.)(?=(.))/$1 == $3 ? $1 ? 1-$2 : 0 : $2/eg;
} while ($x ne $_ and $x=$_);
</syntaxhighlight>
Use hash for complement state
<
$_="_###_##_#_#_#_#__#__\n";
%h=qw(# _ _ #);
Line 3,637 ⟶ 4,266:
s/(?<=(.))(.)(?=(.))/$1 eq $3 ? $1 eq "_" ? "_" : $h{$2} : $2/eg;
} while ($x ne $_ and $x=$_);
</syntaxhighlight>
{{out}} for both versions:
Line 3,652 ⟶ 4,281:
=={{header|Phix}}==
Ludicrously optimised:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"_###_##_#_#_#_#__#__"</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'_'</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">curr</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">toggled</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">curr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'#'</span> <span style="color: #008080;">or</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'#'</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">130</span><span style="color: #0000FF;">-</span><span style="color: #000000;">curr</span>
<span style="color: #000000;">toggled</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">curr</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">toggled</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">toggled</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 8px">
Line 3,683 ⟶ 4,314:
</pre>
And of course I had to have a crack at that Sierpinski_Triangle:
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"________________________#________________________"</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">prev</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'_'</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">curr</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">toggled</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">limit</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">24</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">curr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">prev</span><span style="color: #0000FF;">=</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">curr</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'#'</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">130</span><span style="color: #0000FF;">-</span><span style="color: #000000;">curr</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">prev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">curr</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre style="font-size: 6px">
Line 3,725 ⟶ 4,358:
=={{header|Phixmonti}}==
<
w tolist 0 0 put
0 w 1 + repeat var x2
Line 3,739 ⟶ 4,372:
nl
drop x2
endfor</
=={{header|Picat}}==
<syntaxhighlight lang="picat">go =>
% _ # # # _ # # _ # _ # _ # _ # _ _ # _ _
S = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0],
println(init=S),
run_ca(S),
nl,
println("Some random inits:"),
_ = random2(),
foreach(N in [5,10,20,50])
S2 = [random() mod 2 : _I in 1..N],
run_ca(S2),
nl
end.
%
% Run a CA and show the result.
%
% rule/1 is the default
run_ca(S) =>
run_ca(S,rule).
run_ca(S,Rules) =>
Len = S.length,
All := [S],
Seen = new_map(), % detect fixpoint and cycle
while (not Seen.has_key(S))
Seen.put(S,1),
T = [S[1]] ++ [apply(Rules, slice(S,I-1,I+1)) : I in 2..Len-1] ++ [S[Len]],
All := All ++ [T],
S := T
end,
foreach(A in All) println(A.convert()) end,
writeln(len=All.length).
% Convert:
% 0->"_"
% 1->"#"
convert(L) = Res =>
B = "_#",
Res = [B[L[I]+1] : I in 1..L.length].
% the rules
rule([0,0,0]) = 0. %
rule([0,0,1]) = 0. %
rule([0,1,0]) = 0. % Dies without enough neighbours
rule([0,1,1]) = 1. % Needs one neighbour to survive
rule([1,0,0]) = 0. %
rule([1,0,1]) = 1. % Two neighbours giving birth
rule([1,1,0]) = 1. % Needs one neighbour to survive
rule([1,1,1]) = 0. % Starved to death.</syntaxhighlight>
{{out}}
<pre>init = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________
len = 10
Some random inits:
_###_
_#_#_
__#__
_____
_____
len = 5
_#___##_#_
_____###__
_____#_#__
______#___
__________
__________
len = 6
###__####_#___#___##
#_#__#__##________##
##______##________##
##______##________##
len = 4
______###_#_#___####__#_______#__#___#_####__#_###
______#_##_#____#__#__________________##__#___##_#
_______####___________________________##______####
_______#__#___________________________##______#__#
______________________________________##_________#
______________________________________##_________#
len = 6</pre>
The program is fairly general. Here's the additional code for the rule 30 CA.
<syntaxhighlight lang="picat">go2 =>
N = 4,
Ns = [0 : _ in 1..N],
S = Ns ++ [1] ++ Ns,
run_ca(S, rule30).
% The rules for rule 30
rule30([0,0,0]) = 0.
rule30([0,0,1]) = 1.
rule30([0,1,0]) = 1.
rule30([0,1,1]) = 1.
rule30([1,0,0]) = 1.
rule30([1,0,1]) = 0.
rule30([1,1,0]) = 0.
rule30([1,1,1]) = 0.</syntaxhighlight>
=={{header|PicoLisp}}==
<
(do 10
(prinl Cells)
Line 3,756 ⟶ 4,504:
(link "#") ) ) )
Cells )
(link "_") ) ) ) )</
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 3,771 ⟶ 4,519:
=={{header|Prolog}}==
Works ith SWI-Prolog.
<
maplist(my_write, L), nl,
length(L, N),
Line 3,844 ⟶ 4,592:
L = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0],
one_dimensional_cellular_automata(L).
</syntaxhighlight>
{{out}}
<pre> ?- one_dimensional_cellular_automata.
Line 3,858 ⟶ 4,606:
true .
</pre>
=={{header|Python}}==
===Procedural===
====Python: Straightforward interpretation of spec====
<
printdead, printlive = '_#'
Line 3,930 ⟶ 4,634:
universe.replace('0', printdead).replace('1', printlive) )
universe = offendvalue + universe + offendvalue
universe = ''.join(neighbours2newstate[universe[i:i+3]] for i in range(cellcount))</
{{out}}
<pre>Generation 0: _###_##_#_#_#_#__#__
Line 3,945 ⟶ 4,649:
====Python: Using boolean operators on bits====
The following implementation uses boolean operations to realize the function.
<
nquads = 5
Line 3,960 ⟶ 4,664:
print "Generation %3i: %s" % (i,(''.join(tr[int(t,16)] for t in (fmt%(a>>1)))))
a |= endvals
a = ((a&((a<<1) | (a>>1))) ^ ((a<<1)&(a>>1))) & endmask</
====Python: Sum neighbours == 2====
This example makes use of the observation that a cell is alive in the next generation if the sum with its current neighbours of alive cells is two.
<
>>> for n in range(10):
print(''.join('#' if cell else '_' for cell in gen))
Line 3,981 ⟶ 4,685:
__##________________
__##________________
>>> </
===Composition of pure functions===
Interpreting the rule shown in the task description as Wolfram rule 104, and generalising enough to allow for other rules of this kind:
<
from itertools import islice, repeat
Line 4,191 ⟶ 4,895:
# MAIN -------------------------------------------------
if __name__ == '__main__':
main()</
{{Out}}
<pre>Rule 104:
Line 4,244 ⟶ 4,948:
███ █ █████ ███ ███ ██ ███ ███ ██ ██ █ █████ █
█ █ ██ ██ █ ██ █ ██ █ █████ ███ █ ███ █████ ██ ███ </pre>
=={{header|Quackery}}==
<syntaxhighlight lang="quackery"> [ stack 0 ] is cells ( --> s )
[ dup size cells replace
0 swap witheach
[ char # =
| 1 << ] ] is setup ( $ --> n )
[ 0 swap
cells share times
[ dup i >> 7 &
[ table 0 0 0 1 0 1 1 0 ]
rot 1 << | swap ]
drop 1 << ] is nextline ( n --> n )
[ cells share times
[ dup i 1+ bit &
iff [ char # ]
else [ char _ ]
emit ]
cr drop ] is echoline ( n --> )
[ setup
[ dup echoline
dup nextline
tuck = until ]
echoline ] is automate ( $ --> )
$ "_###_##_#_#_#_#__#__" automate</syntaxhighlight>
{{out}}
<pre>_###_##_#_#_#_#__#__
_#_#####_#_#_#______
__##___##_#_#_______
__##___###_#________
__##___#_##_________
__##____###_________
__##____#_#_________
__##_____#__________
__##________________
__##________________
</pre>
=={{header|R}}==
<
maxgenerations = 10
Line 4,279 ⟶ 5,029:
universe <- cellularAutomata(universe, stayingAlive)
cat(format(i, width=3), deadOrAlive2string(universe), "\n")
}</
{{out}}
Line 4,296 ⟶ 5,046:
=={{header|Racket}}==
<
(define (update cells)
Line 4,322 ⟶ 5,072:
(0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0)
(0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
(0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0) |#</
Below is an alternative implementation using graphical output in the Racket REPL.
It works with DrRacket and Emacs + Geiser.
<
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Line 4,374 ⟶ 5,124:
(apply vc-append 2 (map draw-row (reverse rows)))))
(draw-automaton 104 '(0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0) 10)</
=={{header|Raku}}==
Line 4,386 ⟶ 5,136:
and it makes the implementation a lot easier.
<syntaxhighlight lang="raku"
has $.rule;
has @.cells;
Line 4,421 ⟶ 5,171:
$a = Automaton.new: :rule(90), :cells(flat @padding, 1, @padding);
say $a++ for ^20;</
{{out}}
Line 4,456 ⟶ 5,206:
| # # # # |
| # # # # # # # # |
</pre>
=={{header|Red}}==
<syntaxhighlight lang="rebol">Red [
Purpose: "One-dimensional cellular automata"
Author: "Joe Smith"
]
vals: [0 1 0]
kill: [[0 0] [#[none] 0] [0 #[none]]]
evo: function [petri] [
new-petri: copy petri
while [petri/1] [
if all [petri/-1 = 1 petri/2 = 1] [new-petri/1: select vals petri/1]
if find/only kill reduce [petri/-1 petri/2] [new-petri/1: 0]
petri: next petri new-petri: next new-petri
]
petri: head petri new-petri: head new-petri
clear insert petri new-petri
]
display: function [petri] [
print replace/all (replace/all to-string petri "0" "_") "1" "#"
petri
]
loop 10 [
evo display [1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0]
]
</syntaxhighlight>
{{out}}
<pre>
###_##_#_#_#_#__#_
#_#####_#_#_#_____
_##___##_#_#______
_##___###_#_______
_##___#_##________
_##____###________
_##____#_#________
_##_____#_________
_##_______________
_##_______________
</pre>
=={{header|Retro}}==
<
Assume an array of cells with an initial distribution of live and
Line 4,614 ⟶ 5,407:
~~~
#10 generations
~~~</
=={{header|REXX}}==
This REXX version will show (as a default) 40 generations, or less if the generations of cellular automata repeat.
<
parse arg $ gens . /*obtain optional arguments from the CL*/
if $=='' | $=="," then $=001110110101010 /*Not specified? Then use the default.*/
Line 4,633 ⟶ 5,426:
if $==@ then do; say right('repeats', 40); leave; end /*does it repeat? */
$=@ /*now use the next generation of cells.*/
end /*#*/ /*stick a fork in it, we're all done. */</
'''output''' when using the default input:
<pre>
Line 4,647 ⟶ 5,440:
=={{header|Ring}}==
<
# Project : One-dimensional cellular automata
Line 4,672 ⟶ 5,465:
next
return binsum
</syntaxhighlight>
Output:
<pre>
Line 4,685 ⟶ 5,478:
generation 8: 00110000000000000000
generation 9: 00110000000000000000
</pre>
=={{header|RPL}}==
Rather than assuming fixed values for cells beyond borders, it has been decided to make the board 'circular', as it is the case in many 2D versions. A new generation is directly derived from the output string of the previous generation.
{{works with|Halcyon Calc|4.2.7}}
≪ 1 10 START
DUP DUP 1 1 SUB
OVER DUP SIZE DUP SUB ROT + SWAP +
{ "_##" "#_#" "##_" }
→ gen lives
≪ "" 2 gen SIZE 1 - FOR j
lives gen j 1 - DUP 2 + SUB POS "#" "_" IFTE +
NEXT
≫
NEXT
≫
'CELLS' STO
"_###_##_#_#_#_#__#__" CELLS
{{out}}
<pre>
10: _###_##_#_#_#_#__#__
9: _#_#####_#_#_#______
8: __##___##_#_#_______
7: __##___###_#________
6: __##___#_##_________
5: __##____###_________
4: __##____#_#_________
3: __##_____#__________
2: __##________________
1: __##________________
</pre>
=={{header|Ruby}}==
<
([0]+ary+[0]).each_cons(3).map{|a,b,c| a+b+c == 2 ? 1 : 0}
end
Line 4,700 ⟶ 5,524:
until ary == (new = evolve(ary))
printit ary = new
end</
{{out}}
<pre>.###.##.#.#.#.#..#..
Line 4,713 ⟶ 5,537:
=={{header|Rust}}==
<
match windowed {
[false, true, true] | [true, true, false] => true,
Line 4,750 ⟶ 5,574:
}
}
</syntaxhighlight>
=={{header|Scala}}==
{{works with|Scala|2.8}}
<
def it = Iterator.iterate(s) ( generation =>
("_%s_" format generation).iterator
Line 4,764 ⟶ 5,588:
(it drop 1) zip it takeWhile Function.tupled(_ != _) map (_._2) foreach println
}</
Sample:
Line 4,782 ⟶ 5,606:
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(if (null? petri-dish)
(list)
Line 4,802 ⟶ 5,626:
(- generations 1)))))
(display-evolution (list 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0) 10)</
Output:
<pre>(1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0)
Line 4,818 ⟶ 5,642:
A graphical cellular automaton can be found [http://seed7.sourceforge.net/algorith/graphic.htm#cellauto here].
<
const string: start is "_###_##_#_#_#_#__#__";
Line 4,843 ⟶ 5,667:
g0 := g1;
end for;
end func;</
Output:
Line 4,858 ⟶ 5,682:
__##________________
__##________________
</pre>
=={{header|SequenceL}}==
<
main(args(2)) :=
Line 4,913 ⟶ 5,714:
1 when (left + cells[i] + right) = 2
else
0;</
{{out}}
Line 4,932 ⟶ 5,733:
=={{header|Sidef}}==
{{trans|Perl}}
<
var x = '';
Line 4,941 ⟶ 5,742:
seq.gsub!(/(?<=(.))(.)(?=(.))/, {|s1,s2,s3| s1 == s3 ? (s1 ? 1-s2 : 0) : s2});
(x != seq) && (x = seq) || break;
}</
{{out}}
Line 4,957 ⟶ 5,758:
{{trans|Raku}}
<
method init {
Line 4,989 ⟶ 5,790:
say "|#{auto}|";
auto.next;
}</
{{out}}
Line 5,006 ⟶ 5,807:
=={{header|Tcl}}==
<
set new [list]
for {set i 0} {$i < [llength $a]} {incr i} {
Line 5,041 ⟶ 5,842:
set array $new
print $array
}</
=={{header|Ursala}}==
Line 5,050 ⟶ 5,851:
it according to the rule. The cells are maintained as a list of booleans
(0 and &) but are converted to characters for presentation in the example code.
<
#import nat
Line 5,061 ⟶ 5,862:
#show+
example = ~&?(`#!,`.!)** evolve10 <0,&,&,&,0,&,&,0,&,0,&,0,&,0,0,&,0,0></
output:
<pre>
Line 5,079 ⟶ 5,880:
This implementation writes the calculated patterns into an edit buffer, where the results can viewed and saved into a file if required. The edit buffer also acts as storage during calculations.
<
#9 = Cur_Col
Line 5,096 ⟶ 5,897:
IT("Gen ") Num_Ins(#8, LEFT+NOCR) IT(": ")
Reg_Ins(20)
}</
Sample output:
<
Gen 1: ..#.#####.#.#.#.........
Gen 2: ...##...##.#.#..........
Line 5,108 ⟶ 5,909:
Gen 7: ...##.....#.............
Gen 8: ...##...................
Gen 9: ...##...................</
=={{header|Wart}}==
===Simple===
<
prn l
repeat n
Line 5,251 ⟶ 5,929:
def (next a b c) # next state of b given neighbors a and c
if (and a c) not.b
(or a c) b</
Output looks a little ugly:
Line 5,268 ⟶ 5,946:
Computing the next generation becomes much cleaner once you invest a few LoC in a new datatype.
<
(tag uca (list l len.l))
Line 5,299 ⟶ 5,977:
def (next a b c)
if (and a c) not.b
(or a c) b</
Output is prettier now:
Line 5,317 ⟶ 5,995:
__##________________
__##________________</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
<syntaxhighlight lang="wren">var trans = "___#_##_"
var v = Fn.new { |cell, i| (cell[i] != "_") ? 1 : 0 }
var evolve = Fn.new { |cell, backup|
var len = cell.count - 2
var diff = 0
for (i in 1...len) {
/* use left, self, right as binary number bits for table index */
backup[i] = trans[v.call(cell, i - 1) * 4 + v.call(cell, i) * 2 + v.call(cell, i + 1)]
diff = diff + ((backup[i] != cell[i]) ? 1 : 0)
}
cell.clear()
cell.addAll(backup)
return diff != 0
}
var c = "_###_##_#_#_#_#__#__".toList
var b = "____________________".toList
while(true) {
System.print(c[1..-1].join())
if (!evolve.call(c,b)) break
}</syntaxhighlight>
{{out}}
<pre>
###_##_#_#_#_#__#__
#_#####_#_#_#______
_##___##_#_#_______
_##___###_#________
_##___#_##_________
_##____###_________
_##____#_#_________
_##_____#__________
_##________________
</pre>
=={{header|XPL0}}==
<
int Gen, Now, New, I;
[Now:= $076A_A400;
Line 5,330 ⟶ 6,047:
Now:= New;
];
]</
{{out}}
Line 5,345 ⟶ 6,062:
______##________________________
</pre>
=={{header|zkl}}==
{{trans|Groovy}}
<
right:=line[1,*] + False; // shift left, False fill
left :=T(False).extend(line[0,-1]); // shift right
left.zip(line,right).apply(fcn(hood){ hood.sum(0)==2 });
}</
<
cells:="_###_##_#_#_#_#__#__".split("").apply('==("#")); //-->L(False,True,True,True,False...)
do(10){ cells.apply(chars.get).concat().println(); cells=life1D(cells); }</
Or, using strings instead of lists:
<
right:=line[1,*] + "_"; // shift left, "_" fill
left :="_" + line[0,-1]; // shift right
Line 5,392 ⟶ 6,080:
fcn(a,b,c){ (String(a,b,c) - "_") == "##" and "#" or "_" },
left,line,right).concat();
}</
<
do(10){ cells.println(); cells=life1D(cells); }</
{{out}}
<pre>
Line 5,407 ⟶ 6,095:
__##________________
</pre>
|