One-dimensional cellular automata: Difference between revisions

→‎{{header|Perl 6}}: generalization to any cellular automata of this kind
(→‎{{header|Perl 6}}: slightly shorter + joining output)
(→‎{{header|Perl 6}}: generalization to any cellular automata of this kind)
Line 2,360:
=={{header|Perl 6}}==
 
We'll make a general algorithm capable of computing any cellular automata as defined by Stephen Wolfram's famous book [[wp:A new kind of Science|A new kind of Science]]. As an example, we'll show the automata defined by rule n°90, which shows a [[wp:Sierpinski Triangle|Sierpinski Triangle]]-like figure.
{{works with|Rakudo Star|2012.11}}
 
<lang perl6>class Automata {
Short though it is, this solution even detects stability. Z+ is a zip metaop with addition,
constant patterns = reverse ^8;
and X== is a cross metaop with equality. (Crossing with a scalar always producing a list of the same length.) We have taken the slight liberty of defining a wraparound universe, but it doesn't matter for this example.
has Int $.code;
<lang perl6>my @c = <_ #>;
has @.cells;
my @array = '_###_##_#_#_#_#__#__'.comb »eq» '#';
method gist { <| |>.join: @!cells.map({$_ ?? '#' !! ' '}).join }
method mapping { hash patterns Z=> $.code.fmt("%08b").comb }
method succ {
self.new: :$.code, :cells(
self.mapping{
4 «*« @.cells.rotate(-1)
Z+ 2 «*« @.cells
Z+ @.cells.rotate(1)
}
)
}
}
 
my $size = 50;
repeat until @array eqv my @prev {
my $a = Automata.new: :code(90), :cells( 0 xx $size div 2, 1, 0 xx $size div 2 );
say @c[@prev = @array].join;
@array = ((@array Z+ @array.rotate(1)) Z+ @array.rotate(-1)) X== 2;
}</lang>
 
say $a++ for ^20;</lang>
Output:
 
<pre>| # |
<pre>_###_##_#_#_#_#__#__
| # # |
_#_#####_#_#_#______
| # # |
__##___##_#_#_______
| # # # # |
__##___###_#________
| # # |
__##___#_##_________
| # # # # |
__##____###_________
| # # # # |
__##____#_#_________
| # # # # # # # # |
__##_____#__________
| # # |
__##________________</pre>
| # # # # |
| # # # # |
| # # # # # # # # |
| # # # # |
| # # # # # # # # |
| # # # # # # # # |
| # # # # # # # # # # # # # # # # |
| # # |
| # # # # |
| # # # # |
| # # # # # # # # |</pre>
 
=={{header|PicoLisp}}==
1,934

edits