Jump to content

Elementary cellular automaton: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 21:
{{trans|Nim}}
 
<langsyntaxhighlight lang="11l">V SIZE = 32
V LINES = SIZE I/ 2
V RULE = 90
Line 48:
L 1..LINES
show(state)
evolve(&state)</langsyntaxhighlight>
 
{{out}}
Line 72:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE ROW_LEN="320"
DEFINE MAX_COL="319"
DEFINE MAX_ROW="191"
Line 158:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Elementary_cellular_automaton.png Screenshot from Atari 8-bit computer]
Line 164:
=={{header|Ada}}==
{{works with|Ada 2012}}
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Elementary_Cellular_Automaton is
Line 230:
Generations => 25);
end Elementary_Cellular_Automaton;
</syntaxhighlight>
</lang>
{{Output}}
<pre>Rule 90 :
Line 297:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # elementary cellular automaton #
COMMENT returns the next state from state using rule; s must be at least 2 characters long and consist of # and - only COMMENT
PROC next state = ( STRING state, INT rule )STRING:
Line 339:
test( "---------#---------", 60 );
test( "---------#---------", 90 )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 382:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey 1.1}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">state := StrSplit("0000000001000000000")
rule := 90
output := "Rule: " rule
Line 428:
result .= val = 1 ? "#" : "."
return result
}</langsyntaxhighlight>
{{Output}}
<pre>Rule: 90
Line 444:
=={{header|C}}==
64 cells, edges are cyclic.
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <limits.h>
 
Line 474:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 491:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections;
Line 584:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 644:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <bitset>
#include <stdio.h>
 
Line 674:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> # |
Line 688:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">class Rule(number) satisfies Correspondence<Boolean[3], Boolean> {
shared Byte number;
Line 773:
automaton.evolve();
}
}</langsyntaxhighlight>
{{out}}
<pre>Rule #90
Line 791:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun automaton (init rule &optional (stop 10))
(labels ((next-gen (cells)
(mapcar #'new-cell
Line 811:
do (pretty-print cells))))
 
(automaton '(0 0 0 0 0 0 1 0 0 0 0 0 0) 90)</langsyntaxhighlight>
 
{{Out}}
Line 827:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.string, std.conv, std.range, std.algorithm, std.typecons;
 
enum mod = (in int n, in int m) pure nothrow @safe @nogc => ((n % m) + m) % m;
Line 862:
eca.popFront;
}
}</langsyntaxhighlight>
{{out}}
<pre>Rules: [90, 30, 122]
Line 919:
Pictures of the (nice) generated colored bit-maps : The Escher like [http://www.echolalie.org/echolisp/images/automaton-1.png (task 90 5)] and the fractal like [http://www.echolalie.org/echolisp/images/automaton-2.png (task 22 1)]
 
<langsyntaxhighlight lang="scheme">
(lib 'types) ;; int32 vectors
(lib 'plot)
Line 979:
→ #( #( 0 0 0) #( 0 -5052980 0) #( 0 -5052980 -5052980))
 
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
{{works with|Elixir|1.3}}
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Elementary_cellular_automaton do
def run(start_str, rule, times) do
IO.puts "rule : #{rule}"
Line 1,010:
pad = String.duplicate("0", 14)
str = pad <> "1" <> pad
Elementary_cellular_automaton.run(str, 18, 25)</langsyntaxhighlight>
 
{{out}}
Line 1,044:
=={{header|F_Sharp|F#}}==
===The Function===
<langsyntaxhighlight lang="fsharp">
// Elementary Cellular Automaton . Nigel Galloway: July 31st., 2019
let eca N=
let N=Array.init 8 (fun n->(N>>>n)%2)
Seq.unfold(fun G->Some(G,[|yield Array.last G; yield! G; yield Array.head G|]|>Array.windowed 3|>Array.map(fun n->N.[n.[2]+2*n.[1]+4*n.[0]])))
</syntaxhighlight>
</lang>
===The Task===
<langsyntaxhighlight lang="fsharp">
eca 90 [|0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;1;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0|] |> Seq.take 80 |> Seq.iter(fun n->Array.iter(fun n->printf "%s" (if n=0 then " " else "@"))n; printfn "")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,137:
@ @
</pre>
<langsyntaxhighlight lang="fsharp">
eca 110 [|0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;0;1|] |> Seq.take 80 |> Seq.iter(fun n->Array.iter(fun n->printf "%s" (if n=0 then " " else "@"))n; printfn "")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,225:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs formatting grouping io kernel math math.bits
math.combinatorics sequences sequences.extras ;
 
Line 1,242:
[ dup show-state next-state ] times 2drop ;
 
90 show-automaton</langsyntaxhighlight>
{{out}}
<pre>
Line 1,266:
{{works with|gforth|0.7.3}}
<br>
<langsyntaxhighlight lang="forth">#! /usr/bin/gforth
 
\ Elementary cellular automaton
Line 1,338:
 
bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,348:
* rule 110 [https://commons.wikimedia.org/wiki/File:Rule-110.png]
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#define NCELLS 400
#define border 16
Line 1,416:
end if
key = ucase(inkey)
loop until ucase(key) = "Q"</langsyntaxhighlight>
 
=={{header|Fōrmulæ}}==
Line 1,427:
 
=={{header|Furor}}==
<syntaxhighlight lang="furor">
<lang Furor>
argc 4 < { ."Usage: " 0 argv sprint SPACE 1 argv sprint SPACE ."rule size\n"
."The \"rule\" and \"size\" are numbers.\n"
Line 1,471:
 
// =================================================
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,515:
=={{header|GFA Basic}}==
 
<syntaxhighlight lang="text">
'
' Elementary One-Dimensional Cellular Automaton
Line 1,641:
RETURN result%
ENDFUNC
</syntaxhighlight>
</lang>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,688:
output()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,720:
Straight-forward implementation of CA on a cyclic domain, using immutable arrays:
 
<langsyntaxhighlight Haskelllang="haskell">import Data.Array (listArray, (!), bounds, elems)
 
step rule a = listArray (l,r) res
Line 1,728:
[rule (a!(r-1)) (a!r) (a!l) ]
 
runCA rule = iterate (step rule)</langsyntaxhighlight>
 
The following gives decoding of the CA rule and prepares the initial CA state:
<langsyntaxhighlight Haskelllang="haskell">rule n l x r = n `div` (2^(4*l + 2*x + r)) `mod` 2
 
initial n = listArray (0,n-1) . center . padRight n
where
padRight n lst = take n $ lst ++ repeat 0
center = take n . drop (n `div` 2+1) . cycle</langsyntaxhighlight>
 
Finally the IO stuff:
<langsyntaxhighlight Haskelllang="haskell">displayCA n rule init = mapM_ putStrLn $ take n result
where result = fmap display . elems <$> runCA rule init
display 0 = ' '
display 1 = '*'</langsyntaxhighlight>
 
{{Out}}
Line 1,792:
The cyclic CA domain is represented by an infinite ''zipper list''. First we provide the datatype, the viewer and constructor:
 
<langsyntaxhighlight Haskelllang="haskell">{-# LANGUAGE DeriveFunctor #-}
 
import Control.Comonad
Line 1,805:
-- zero cycle length ensures that elements of the empty cycle will never be accessed
fromList lst = let x:::r = Inf.cycle lst
in Cycle (length lst) (last lst) x r</langsyntaxhighlight>
 
In order to run the CA on the domain we make it an instance of <code>Comonad</code> class. Running the CA turns to be just an iterative comonadic ''extension'' of the rule:
 
<langsyntaxhighlight Haskelllang="haskell">instance Comonad Cycle where
extract (Cycle _ _ x _) = x
duplicate x@(Cycle n _ _ _) = fromList $ take n $ iterate shift x
Line 1,816:
step rule (Cycle _ l x (r:::_)) = rule l x r
 
runCA rule = iterate (=>> step rule)</langsyntaxhighlight>
 
 
Rule definition and I/O routine is the same as in Array-based solution:
 
<langsyntaxhighlight Haskelllang="haskell">rule n l x r = n `div` (2^(4*l + 2*x + r)) `mod` 2
 
initial n lst = fromList $ center $ padRight n lst
Line 1,831:
where result = fmap display . view <$> runCA rule init
display 0 = ' '
display 1 = '*'</langsyntaxhighlight>
 
See also [[Elementary cellular automaton/Infinite length#Haskell]]
Line 1,839:
We'll define a state transition mechanism, and then rely on the language for iteration and display:
 
<langsyntaxhighlight Jlang="j"> next=: ((8$2) #: [) {~ 2 #. 1 - [: |: |.~"1 0&_1 0 1@]
' *'{~90 next^:(i.9) 0 0 0 0 0 0 1 0 0 0 0 0
*
Line 1,849:
* *
* * * *
* * </langsyntaxhighlight>
 
Or, we can view this on a larger scale, graphically:
 
<langsyntaxhighlight Jlang="j"> require'viewmat'
viewmat 90 next^:(i.200) 0=i:200</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
Line 1,940:
});
}
}</langsyntaxhighlight>
[[File:ca java.png|900px]]
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">const alive = '#';
const dead = '.';
 
Line 1,989:
}
 
displayCA(90, 57, 31, 28);</langsyntaxhighlight>
{{out}}
<pre>
Line 2,036:
 
'''Helper functions'''
<langsyntaxhighlight lang="jq"># The ordinal value of the relevant states:
def states:
{"111": 1, "110": 2, "101": 3, "100": 4, "011": 5, "010": 6, "001": 7, "000": 8};
Line 2,062:
| .[1:] # remove the leading 0
| join("")
end ;</langsyntaxhighlight>
 
'''Main function'''
<langsyntaxhighlight lang="jq"># "rule" can be given as a decimal or string of 0s and 1s:
def automaton(rule; steps):
 
Line 2,089:
| gsub("0"; ".") # pretty print
| gsub("1"; "#")
</syntaxhighlight>
</lang>
 
 
Line 2,108:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">
const lines = 10
const start = ".........#........."
Line 2,137:
end
end
</langsyntaxhighlight> {{output}} <pre>
Using Rule 90:
.........#.........
Line 2,177:
=={{header|Kotlin}}==
{{trans|C++}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
import java.util.BitSet
Line 2,214:
evolve(state)
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,238:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">local CA = {
state = "..............................#..............................",
bstr = { [0]="...", "..#", ".#.", ".##", "#..", "#.#", "##.", "###" },
Line 2,263:
print(string.format("%-66s%-66s%-66s%-61s", ca[1].state, ca[2].state, ca[3].state, ca[4].state))
for j = 1, 4 do ca[j]:evolve() end
end</langsyntaxhighlight>
{{out}}
<pre style="font-size:50%">..............................#.............................. ..............................#.............................. ..............................#.............................. ..............................#..............................
Line 2,333:
Mathematica provides built-in functions for cellular automata. For example visualizing the first 100 rows of rule 30 on an 8-bit grid with a single initial cell:
 
<langsyntaxhighlight Mathematicalang="mathematica">ArrayPlot[CellularAutomaton[30, {0, 0, 0, 0, 1, 0, 0, 0}, 100]]</langsyntaxhighlight>
 
=={{header|MATLAB}}==
<langsyntaxhighlight MATLABlang="matlab">function init = cellularAutomaton(rule, init, n)
init(n + 1, :) = 0;
for k = 1 : n
init(k + 1, :) = bitget(rule, 1 + filter2([4 2 1], init(k, :)));
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight MATLABlang="matlab">>> char(cellularAutomaton(90, ~(-15:15), 15) * 10 + 32)
ans =
*
Line 2,359:
* * * * * * * *
* * * * * * * *
* * * * * * * * * * * * * * * *</langsyntaxhighlight>
 
 
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import bitops
 
const
Line 2,416:
for _ in 1..Lines:
show(state)
evolve(state)</langsyntaxhighlight>
 
{{out}}
Line 2,438:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">clear all
E=200;
idx=round(E/2);
Line 2,453:
endfor
imagesc(reshape(z,E,E)'); % Medland map
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use strict;
use warnings;
 
Line 2,492:
for (1..40) {
print "|$a|\n"; $a->next;
}</langsyntaxhighlight>
{{out}}
<pre>| # |
Line 2,537:
=={{header|Phix}}==
String-based solution
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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: #0000FF;">,</span>
Line 2,556:
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
Output matches that of D and Python:wrap for rule = 90, 30, 122 (if you edit/run 3 times)
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de dictionary (N)
(extract
'((A B)
Line 2,587:
(cellular
".........#........."
90 )</langsyntaxhighlight>
{{out}}
<pre>
Line 2,603:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">play :- initial(I), do_auto(50, I).
 
initial([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0]).
Line 2,633:
 
writ(0) :- write('.').
writ(1) :- write(1).</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,640:
:''You can deal with the limit conditions (what happens on the borders of the space) in any way you please.''
 
<langsyntaxhighlight lang="python">def eca(cells, rule):
lencells = len(cells)
c = "0" + cells + "0" # Zero pad the ends
Line 2,660:
i = data[0]
cells = data[1:]
print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('1', '#')))</langsyntaxhighlight>
 
{{out}}
Line 2,718:
===Python: wrap===
The ends of the cells wrap-around.
<langsyntaxhighlight lang="python">def eca_wrap(cells, rule):
lencells = len(cells)
rulebits = '{0:08b}'.format(rule)
Line 2,735:
cells = data[1:]
print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('1', '#')))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,795:
 
Pad and extend with inverse of end cells on each iteration.
<langsyntaxhighlight lang="python">def _notcell(c):
return '0' if c == '1' else '1'
 
Line 2,817:
i = data[0]
cells = ['%s%s%s' % (' '*(lines - i), c, ' '*(lines - i)) for c in data[1:]]
print('%2i: %s' % (i, ' '.join(cells).replace('0', '.').replace('1', '#')))</langsyntaxhighlight>
 
{{out}}
Line 2,849:
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> ( the Cellular Automaton is on the stack as 3 items, the )
( Rule (R), the Size of the space (S) and the Current )
( state (C). make-ca sets this up from a string indicating )
Line 2,902:
say "Rule 30, 50 generations:" cr cr
$ ".........#........." 30 50 generations</langsyntaxhighlight>
 
{{out}}
Line 2,967:
unmodified for [[Elementary cellular automaton/Infinite length]].
 
<langsyntaxhighlight lang="racket">#lang racket
(require racket/fixnum)
(provide usable-bits/fixnum usable-bits/fixnum-1 CA-next-generation
Line 3,052:
(show-automaton v #:step step #:sig-bits 19)
(newline)
(ng/122/19-bits v o)))</langsyntaxhighlight>
 
{{out}}
Line 3,104:
Using the <tt>Automaton</tt> class defined at [[One-dimensional_cellular_automata#Raku]]:
 
<syntaxhighlight lang="raku" perl6line>class Automaton {
has $.rule;
has @.cells;
Line 3,128:
:cells(flat @padding, 1, @padding);
 
say $a++ for ^10;</langsyntaxhighlight>
 
{{out}}
Line 3,145:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class ElemCellAutomat
include Enumerable
Line 3,166:
 
eca = ElemCellAutomat.new('1'.center(39, "0"), 18, true)
eca.take(30).each{|line| puts line.tr("01", ".#")}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,203:
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
<lang Rust>
fn main() {
struct ElementaryCA {
Line 3,246:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,286:
=={{header|Scala}}==
===Java Swing Interoperability===
<langsyntaxhighlight Scalalang="scala">import java.awt._
import java.awt.event.ActionEvent
 
Line 3,358:
})
 
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; uses SRFI-1 library http://srfi.schemers.org/srfi-1/srfi-1.html
 
(define (evolve ls r)
Line 3,389:
n))
 
(automaton '(0 1 0 0 0 1 0 1 0 0 1 1 1 1 0 0 0 0 0 1) 30 20)</langsyntaxhighlight>
{{out}}
 
Line 3,417:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">class Automaton(rule, cells) {
 
method init {
Line 3,449:
print "|#{auto}|\n"
auto.next
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,466:
=={{header|Tcl}}==
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
oo::class create ElementaryAutomaton {
Line 3,505:
puts [string map "0 . 1 #" [join $s ""]]
}
}</langsyntaxhighlight>
Demonstrating:
<langsyntaxhighlight lang="tcl">puts "Rule 90 (with default state):"
ElementaryAutomaton create rule90 90
rule90 run 20
puts "\nRule 122:"
[ElementaryAutomaton new 122] run 25 "..........#......…."</langsyntaxhighlight>
{{out}}
<pre>
Line 3,570:
{{works with|Bourne Again SHell}}
{{works with|Korn Shell}}
<langsyntaxhighlight lang="bash">function print_cells {
local chars=(. '#') cell
for cell; do
Line 3,606:
 
automaton "$@"
</syntaxhighlight>
</lang>
{{Out}}
<pre> 0: ................#...............
Line 3,629:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/fmt" for Conv
 
var SIZE = 32
Line 3,660:
show.call(state)
evolve.call(state)
}</langsyntaxhighlight>
 
{{out}}
Line 3,684:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn rule(n){ n=n.toString(2); "00000000"[n.len() - 8,*] + n }
fcn applyRule(rule,cells){
cells=String(cells[-1],cells,cells[0]); // wrap cell ends
(cells.len() - 2).pump(String,'wrap(n){ rule[7 - cells[n,3].toInt(2)] })
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">cells:="0000000000000001000000000000000"; r90:=rule(90); map:=" *";
r90.println(" rule 90");
do(20){ cells.apply(map.get).println(); cells=applyRule(r90,cells); }</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.