One-dimensional cellular automata: Difference between revisions
m
syntax highlighting fixup automation
Drkameleon (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 19:
{{trans|Python}}
<
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))</
{{out}}
Line 40:
=={{header|8th}}==
<
\ one-dimensional automaton
Line 73:
bye
</syntaxhighlight>
=={{header|ACL2}}==
<
(if (endp (rest cells))
nil
Line 108:
nil
(prog2$ (pretty-row (first out))
(pretty-output (rest out)))))</
=={{header|Action!}}==
<
IF prev='. AND curr='# AND next='# THEN
RETURN ('#)
Line 148:
FI
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/One-dimensional_cellular_automata.png Screenshot from Atari 8-bit computer]
Line 165:
=={{header|Ada}}==
<
procedure Cellular_Automata is
Line 206:
Step (Culture);
end loop;
end Cellular_Automata;</
The implementation defines Petri dish type with Boolean items
Line 231:
{{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 273:
FI;
universe := next universe
OD</
{{out}}
<pre>
Line 293:
{{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 327:
next universe[UPB universe] := couple(universe[UPB universe - 1: ]);
universe := next universe
OD</
{{out}}
<pre>
Line 344:
=={{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 363:
generation := generation + 1
end while_not_finished
end.</
{{out}}
<pre>
Line 379:
=={{header|Arturo}}==
<
ary: [0] ++ arr ++ [0]
ret: new []
Line 405:
newGen: evolve arr
printIt newGen
]</
{{out}}
Line 421:
=={{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 443:
GuiClose: ; exit when GUI is closed
ExitApp</
=={{header|AWK}}==
<
BEGIN {
edge = 1
Line 516:
}
}
</syntaxhighlight>
{{out}}
Line 532:
</pre>
<
cat automata.awk :
Line 575:
} while (str_ != str_previous)
}
</syntaxhighlight>
{{out}}
Line 596:
{{works with|QuickBasic|4.5}}
{{trans|Java}}
<
DECLARE FUNCTION getNeighbors! (group$)
CLS
Line 648:
NEXT i
life$ = newGen$
END FUNCTION</
{{out}}
<pre>Generation 0 : _###_##_#_#_#_#__#__
Line 662:
==={{header|FreeBASIC}}===
<
randomize timer
Line 704:
'or Q to exit
loop
wend</
==={{header|Sinclair ZX81 BASIC}}===
Works with the unexpanded (1k RAM) ZX81.
<
20 LET G=1
30 PRINT N$
Line 726:
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 734:
=={{header|BASIC256}}==
<
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)
Line 749:
start[j] = sgtes[j]
next j
next k</
=={{header|Batch File}}==
This implementation will not stop showing generations, unless the cellular automata is already stable.
<
setlocal enabledelayedexpansion
Line 810:
set proc=%newgen%
goto :nextgen
::/THE (LLLLLLOOOOOOOOOOOOONNNNNNNNGGGGGG.....) PROCESSOR</
{{out}}
<pre> | __###__##_#_##_###__######_###_#####_#__##_____#_#_#######__ |
Line 824:
=={{header|BBC BASIC}}==
<
rule$() = "0", "0", "0", "1", "0", "1", "1", "0"
Line 836:
NEXT cell%
SWAP now$, next$
NEXT generation%</
{{out}}
<pre>Generation 0: 01110110101010100100
Line 850:
=={{header|Befunge}}==
<
" !!! !! ! ! ! ! ! " ,*25 <v
" " ,*25,,,,,,,,,,,,,,,,,,,,<v
Line 865:
^ >$$$$320p10g1+:9`v > >$"!"> 20g10g1+p 20g1+:20p
^ v_10p10g
> ^</
=={{header|Bracmat}}==
<
= n z
. @( !arg
Line 897:
& evolve$!S:?S
)
);</
{{out}}
<pre>11101101010101001001
Line 910:
=={{header|C}}==
<
#include <string.h>
Line 937:
do { printf(c + 1); } while (evolve(c + 1, b + 1, sizeof(c) - 3));
return 0;
}</
{{out}}
<pre>###_##_#_#_#_#__#__
Line 950:
Similar to above, but without a backup string:
<
char trans[] = "___#_##_";
Line 976:
do { printf(c + 1); } while (evolve(c + 1, sizeof(c) - 3));
return 0;
}</
=={{header|C sharp}}==
<
using System.Collections.Generic;
Line 1,017:
}
}
}</
=={{header|C++}}==
Uses std::bitset for efficient packing of bit values.
<
#include <bitset>
#include <string>
Line 1,049:
std::cout << std::endl;
}
}</
{{out}}
Line 1,064:
=={{header|Ceylon}}==
<
shared Character character;
string => character.string;
Line 1,129:
print("generation `` ++generation `` ``automata``");
}
}</
=={{header|Clojure}}==
<
(:require (clojure.contrib (string :as s))))
Line 1,147:
'()
(cons cells (generate (dec n) (next-gen cells)))))
</syntaxhighlight>
<
(println cells))
_###_##_#_#_#_#__#__
Line 1,160:
__##________________
nil
</syntaxhighlight>
Another way:
<
(require '[clojure.string :as str])
Line 1,188:
(do (println g)
(recur (compute-next-genr g)
(inc i)))))</
Yet another way, easier to understand
<
(def rules
{
Line 1,216:
(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,329:
end-perform
.
</syntaxhighlight>
{{out}}
Line 1,353:
_##_____#__________
_##________________={{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,386:
simulate (c == '#' for c in ".###.##.#.#.#.#..#..")
</syntaxhighlight>
{{out}}
<pre>
Line 1,404:
=={{header|Common Lisp}}==
Based upon the Ruby version.
<
(assert (> (length x) 1))
(coerce x 'simple-bit-vector))
Line 1,431:
do (princ (if (zerop (bit value i)) #\. #\#)
stream))
(terpri stream))</
<
for value = #*01110110101010100100 then (next-cycle value)
until (equalp value previous-value)
Line 1,445:
..##....#.#.........
..##.....#..........
..##................</
=={{header|D}}==
<
import std.stdio, std.algorithm;
Line 1,466:
writeln;
}
}</
{{out}}
<pre>__###_##_#_#_#_#__#___
Line 1,481:
===Alternative Version===
{{trans|Raku}}
<
import std.stdio, std.algorithm, std.range;
Line 1,493:
A.swap(B);
} while (A != B);
}</
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 1,508:
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,531:
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,555:
PrintLn('');
end;
</syntaxhighlight>
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 1,570:
=={{header|Déjà Vu}}==
<
0 ]
repeat size:
Line 1,605:
return print-state drop
run 60</
{{out}}
<pre>001110011010110111001111110111011111010011000001010111111100
Line 1,619:
=={{header|E}}==
<
var result := state(0, 1) # fixed left cell
for i in 1..(state.size() - 2) {
Line 1,636:
}
return state
}</
<
" " => " ",
" #" => " ",
Line 1,660:
8 | ##
9 | ##
# value: " ## "</
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,736:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,753:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def run(list, gen \\ 0) do
print(list, gen)
Line 1,773:
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,790:
=={{header|Elm}}==
<
import List exposing (length, tail, reverse, concat, head, append, map3)
import Html exposing (Html, div, h1, text)
Line 1,879:
, update = update
, subscriptions = subscriptions
}</
Link to live demo: https://dc25.github.io/oneDimensionalCellularAutomataElm/
=={{header|Erlang}}==
<
-module(ca).
-compile(export_all).
Line 1,933:
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,947:
8: ___##_________________
9: ___##_________________
</syntaxhighlight>
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM ONEDIM_AUTOMATA
Line 1,984:
END FOR
END PROGRAM
</syntaxhighlight>
{{out}}
<pre>
Line 2,010:
=={{header|Euphoria}}==
<
function rules(integer tri)
Line 2,055:
printf(1,"Generation %d: ",n)
print_gen(gen)</
{{out}}
Line 2,069:
=={{header|Factor}}==
<
IN: cellular
Line 2,090:
10 [ dup print-cellular step ] times print-cellular ;
MAIN: main-cellular
</syntaxhighlight>
<pre>( scratchpad ) "cellular" run
_###_##_#_#_#_#__#__
Line 2,105:
=={{header|Fantom}}==
<
class Automaton
{
Line 2,136:
}
}
</syntaxhighlight>
=={{header|FOCAL}}==
<
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
Line 2,159:
7.1 T "#"
8.1 T "."</
{{output}}
<pre>
Line 2,175:
=={{header|Forth}}==
<
0 do dup 1 and c, 2/ loop drop ;
Line 2,199:
.state 1 do gen .state loop ;
10 life1d</
ouput
<syntaxhighlight lang="text">
### ## # # # # #
# ##### # # #
Line 2,213:
##
## ok
</syntaxhighlight>
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
IMPLICIT NONE
Line 2,266:
END SUBROUTINE Drawgen
END PROGRAM LIFE_1D</
{{out}}
<pre>
Line 2,282:
=={{header|GFA Basic}}==
<syntaxhighlight lang="text">
'
' One Dimensional Cellular Automaton
Line 2,396:
RETURN result%
ENDFUNC
</syntaxhighlight>
=={{header|Go}}==
===Sequential===
<
import "fmt"
Line 2,437:
return g0[1:last]
}
}</
{{out}}
<pre>
Line 2,457:
Separate read and write phases.
Single array of cells.
<
import (
Line 2,511:
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,543:
=={{header|Haskell}}==
<
import System.Random (newStdGen, randomRs)
Line 2,573:
. take 36
. randomRs (0, 1)
)</
{{Out}}
For example:
Line 2,587:
=={{header|Icon}} and {{header|Unicon}}==
<
# One dimensional Cellular automaton
record Automaton(size, cells)
Line 2,624:
}
end
</syntaxhighlight>
An alternative approach is to represent the automaton as a string.
Line 2,635:
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,650:
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,671:
=={{header|J}}==
<
{{out|Example use}}
<
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
Line 2,683:
__##____#_#_________
__##_____#__________
__##________________</
Alternative implementation:
<
'_#'{~ (3 ((|.n#:~8#2) {~ #.)\ 0,],0:)^:(i.m)
)</
{{out|Example use}}
<
_###_##_#_#_#_#__#__
_#_#####_#_#_#______
Line 2,701:
__##____#_#_________
__##_____#__________
__##________________</
=={{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,747:
return ans;
}
}</
{{out}}
<pre>Generation 0: _###_##_#_#_#_#__#__
Line 2,763:
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,793:
}while(evolve(c));
}
}</
{{out}}
<pre>###_##_#_#_#_#__#__
Line 2,812:
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,824:
}
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,853:
# 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,864:
** * *
** *
**</
=={{header|Julia}}==
This solution creates an automaton with with either empty or periodic bounds. The empty bounds case, is typical of many of the solutions here. The periodic bounds case is a typical physics approach where, in effect, the beginning and end of the list touch each other to form a circular rather than linear array. In practice, the effects of boundary conditions are subtle for long arrays.
<syntaxhighlight lang="julia">
function next_gen(a::BitArray{1}, isperiodic=false)
b = copy(a)
Line 2,904:
a = next_gen(a, true)
end
</syntaxhighlight>
{{out}}
Line 2,927:
=={{header|K}}==
<
{{out|Example usage}}
<
_XXX_XX_X_X_X_X__X__
_X_XXXXX_X_X_X______
Line 2,940:
__XX_____X__________
__XX________________
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|C}}
<
val trans = "___#_##_"
Line 2,970:
}
while (evolve(c,b))
}</
{{out}}
Line 2,988:
{{works with|Just BASIC}}
{{works with|Run BASIC}}
<
' does not wrap so fails for some rules
Line 3,012:
next j
end</
=={{header|Locomotive Basic}}==
<
20 FOR k=1 TO n
30 FOR j=1 TO w
Line 3,024:
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</
{{out}}
Line 3,031:
=={{header|Logo}}==
{{works with|UCB Logo}}
<
make "generations 9
Line 3,068:
end
CA_1D :cell_list :generations</
{{out}}
<pre>
Line 3,084:
=={{header|Lua}}==
<
f = { 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0 }
Line 3,115:
Output( f, l )
end </
{{out}}
<pre>0: _###_##_#_#_#_#__#__
Line 3,129:
=={{header|M4}}==
<
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
Line 3,164:
for(`j',1,10,
`show(x)`'evolve(`x',`y')`'swap(`x',x,`y')
')`'show(x)</
{{out}}
Line 3,183:
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Built-in function:
<
Print @@@ (% /. {1 -> "#", 0 -> "."});</
For succinctness, an integral rule can be used:
<
{{out}}
<
#.#####.#.#.#....
.##...##.#.#.....
Line 3,200:
.##..............
.##..............
.##..............</
=={{header|MATLAB}} / {{header|Octave}}==
<
V='_#';
while n>=0;
Line 3,211:
v = v(3:end)==2;
end;
end</
{{out}}
<pre>octave:27> one_dim_cell_automata('01110110101010100100'=='1',20);
Line 3,233:
but it segfaults when trying to use <code>BOOLEAN</code> types,
so we use <code>INTEGER</code> instead.
<
IMPORT IO, Fmt, Word;
Line 3,275:
Step(culture);
END;
END Cell.</
{{out}}
<pre>
Line 3,291:
=={{header|MontiLang}}==
<
35 VAR height .
FOR length 0 ENDFOR 1 0 ARR VAR list .
Line 3,369:
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,382:
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,437:
if map2 == map: break
map = map2</
{{out}}
<pre>_###_##_#_#_#_#__#____________
Line 3,451:
'''Using a string character counting method''':
<
const
Line 3,478:
q0 = q1
q1 = evolve(q0)
echo(q1)</
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 3,492:
'''Using nested functions and method calling style:'''
<
proc evolveInto(x, t : var string) =
for i in x.low..x.high:
Line 3,512:
swap t, x
cellAutomata()</
{{out}}
Line 3,528:
=={{header|OCaml}}==
<
try g.(i)
with _ -> 0
Line 3,556:
else print_char '#'
done;
print_newline()</
put the code above in a file named "life.ml",
Line 3,592:
=={{header|Oforth}}==
<
| i s |
l byteSize dup ->s String newSize
Line 3,604:
: gen( l n -- )
l dup .cr #[ nextGen dup .cr ] times( n ) drop ;</
{{out}}
Line 3,624:
=={{header|Oz}}==
<
A0 = {List.toTuple unit "_###_##_#_#_#_#__#__"}
Line 3,659:
do
{System.showInfo "Gen. "#I#": "#{Record.toList A}}
end</
{{out}}
Line 3,679:
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,697:
[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,772:
NextRow(@row[0],High(row));
end;
end.</
{{Out}}<pre>
__###_##_#_#_#_#__#__
Line 3,790:
Convert cells to zeros and ones to set complement state
<
$_="_###_##_#_#_#_#__#__\n";
do {
Line 3,798:
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,808:
s/(?<=(.))(.)(?=(.))/$1 eq $3 ? $1 eq "_" ? "_" : $h{$2} : $2/eg;
} while ($x ne $_ and $x=$_);
</syntaxhighlight>
{{out}} for both versions:
Line 3,823:
=={{header|Phix}}==
Ludicrously optimised:
<!--<
<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>
Line 3,841:
<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>
<!--</
{{out}}
<pre style="font-size: 8px">
Line 3,856:
</pre>
And of course I had to have a crack at that Sierpinski_Triangle:
<!--<
<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>
Line 3,870:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre style="font-size: 6px">
Line 3,900:
=={{header|Phixmonti}}==
<
w tolist 0 0 put
0 w 1 + repeat var x2
Line 3,914:
nl
drop x2
endfor</
=={{header|Picat}}==
<
% _ # # # _ # # _ # _ # _ # _ # _ _ # _ _
S = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0],
Line 3,967:
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.</
{{out}}
Line 4,015:
The program is fairly general. Here's the additional code for the rule 30 CA.
<
N = 4,
Ns = [0 : _ in 1..N],
Line 4,029:
rule30([1,0,1]) = 0.
rule30([1,1,0]) = 0.
rule30([1,1,1]) = 0.</
=={{header|PicoLisp}}==
<
(do 10
(prinl Cells)
Line 4,046:
(link "#") ) ) )
Cells )
(link "_") ) ) ) )</
{{out}}
<pre>_###_##_#_#_#_#__#__
Line 4,061:
=={{header|Prolog}}==
Works ith SWI-Prolog.
<
maplist(my_write, L), nl,
length(L, N),
Line 4,134:
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 4,150:
=={{header|PureBasic}}==
<
Dim cG.i(21)
Dim nG.i(21)
Line 4,180:
Until Gen > 9
PrintN("Press any key to exit"): Repeat: Until Inkey() <> ""</
{{out}}
<pre>Generation 0: _###_##_#_#_#_#__#__
Line 4,196:
===Procedural===
====Python: Straightforward interpretation of spec====
<
printdead, printlive = '_#'
Line 4,220:
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 4,235:
====Python: Using boolean operators on bits====
The following implementation uses boolean operations to realize the function.
<
nquads = 5
Line 4,250:
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 4,271:
__##________________
__##________________
>>> </
===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,481:
# MAIN -------------------------------------------------
if __name__ == '__main__':
main()</
{{Out}}
<pre>Rule 104:
Line 4,537:
=={{header|Quackery}}==
<
[ dup size cells replace
Line 4,564:
echoline ] is automate ( $ --> )
$ "_###_##_#_#_#_#__#__" automate</
{{out}}
Line 4,583:
=={{header|R}}==
<
maxgenerations = 10
Line 4,615:
universe <- cellularAutomata(universe, stayingAlive)
cat(format(i, width=3), deadOrAlive2string(universe), "\n")
}</
{{out}}
Line 4,632:
=={{header|Racket}}==
<
(define (update cells)
Line 4,658:
(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,710:
(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,722:
and it makes the implementation a lot easier.
<syntaxhighlight lang="raku"
has $.rule;
has @.cells;
Line 4,757:
$a = Automaton.new: :rule(90), :cells(flat @padding, 1, @padding);
say $a++ for ^20;</
{{out}}
Line 4,795:
=={{header|Red}}==
<
Purpose: "One-dimensional cellular automata"
Author: "Joe Smith"
Line 4,821:
evo display [1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0]
]
</syntaxhighlight>
{{out}}
Line 4,838:
=={{header|Retro}}==
<
Assume an array of cells with an initial distribution of live and
Line 4,993:
~~~
#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 5,012:
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 5,026:
=={{header|Ring}}==
<
# Project : One-dimensional cellular automata
Line 5,051:
next
return binsum
</syntaxhighlight>
Output:
<pre>
Line 5,067:
=={{header|Ruby}}==
<
([0]+ary+[0]).each_cons(3).map{|a,b,c| a+b+c == 2 ? 1 : 0}
end
Line 5,079:
until ary == (new = evolve(ary))
printit ary = new
end</
{{out}}
<pre>.###.##.#.#.#.#..#..
Line 5,092:
=={{header|Rust}}==
<
match windowed {
[false, true, true] | [true, true, false] => true,
Line 5,129:
}
}
</syntaxhighlight>
=={{header|Scala}}==
{{works with|Scala|2.8}}
<
def it = Iterator.iterate(s) ( generation =>
("_%s_" format generation).iterator
Line 5,143:
(it drop 1) zip it takeWhile Function.tupled(_ != _) map (_._2) foreach println
}</
Sample:
Line 5,161:
=={{header|Scheme}}==
{{Works with|Scheme|R<math>^5</math>RS}}
<
(if (null? petri-dish)
(list)
Line 5,181:
(- 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 5,197:
A graphical cellular automaton can be found [http://seed7.sourceforge.net/algorith/graphic.htm#cellauto here].
<
const string: start is "_###_##_#_#_#_#__#__";
Line 5,222:
g0 := g1;
end for;
end func;</
Output:
Line 5,263:
=={{header|SequenceL}}==
<
main(args(2)) :=
Line 5,292:
1 when (left + cells[i] + right) = 2
else
0;</
{{out}}
Line 5,311:
=={{header|Sidef}}==
{{trans|Perl}}
<
var x = '';
Line 5,320:
seq.gsub!(/(?<=(.))(.)(?=(.))/, {|s1,s2,s3| s1 == s3 ? (s1 ? 1-s2 : 0) : s2});
(x != seq) && (x = seq) || break;
}</
{{out}}
Line 5,336:
{{trans|Raku}}
<
method init {
Line 5,368:
say "|#{auto}|";
auto.next;
}</
{{out}}
Line 5,385:
=={{header|Tcl}}==
<
set new [list]
for {set i 0} {$i < [llength $a]} {incr i} {
Line 5,420:
set array $new
print $array
}</
=={{header|Ursala}}==
Line 5,429:
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,440:
#show+
example = ~&?(`#!,`.!)** evolve10 <0,&,&,&,0,&,&,0,&,0,&,0,&,0,0,&,0,0></
output:
<pre>
Line 5,458:
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,475:
IT("Gen ") Num_Ins(#8, LEFT+NOCR) IT(": ")
Reg_Ins(20)
}</
Sample output:
<
Gen 1: ..#.#####.#.#.#.........
Gen 2: ...##...##.#.#..........
Line 5,487:
Gen 7: ...##.....#.............
Gen 8: ...##...................
Gen 9: ...##...................</
=={{header|Visual Basic .NET}}==
Line 5,493:
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.
<
Module CellularAutomata
Line 5,597:
Return sw.ToString()
End Function
End Module</
Output:
Line 5,614:
=={{header|Wart}}==
===Simple===
<
prn l
repeat n
Line 5,630:
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,647:
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,678:
def (next a b c)
if (and a c) not.b
(or a c) b</
Output is prettier now:
Line 5,699:
=={{header|Wren}}==
{{trans|Kotlin}}
<
var v = Fn.new { |cell, i| (cell[i] != "_") ? 1 : 0 }
Line 5,721:
System.print(c[1..-1].join())
if (!evolve.call(c,b)) break
}</
{{out}}
Line 5,737:
=={{header|XPL0}}==
<
int Gen, Now, New, I;
[Now:= $076A_A400;
Line 5,748:
Now:= New;
];
]</
{{out}}
Line 5,766:
=={{header|Yabasic}}==
{{trans|Locomotive_Basic}}
<
20 FOR k=1 TO n
30 FOR j=1 TO w
Line 5,774:
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</
Other solution
<
dim x$(1)
Line 5,791:
next j
print
next k</
=={{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,810:
fcn(a,b,c){ (String(a,b,c) - "_") == "##" and "#" or "_" },
left,line,right).concat();
}</
<
do(10){ cells.println(); cells=life1D(cells); }</
{{out}}
<pre>
|