Elementary cellular automaton: Difference between revisions

→‎{{header|Perl 6}}: Combine the two solutions into one, and improve. (Hyper ops understand precedence and seem faster than X Z.)
m (→‎{{header|Sidef}}: modified the code to work with Sidef 2.30)
(→‎{{header|Perl 6}}: Combine the two solutions into one, and improve. (Hyper ops understand precedence and seem faster than X Z.))
Line 969:
 
<lang perl6>class Automaton {
has ($.rule, @.cells);
has @.cells;
method gist { <| |>.join: @!cells.map({+$_ ?? '#' !! ' '}).join }
methodhas @.code {= $!rule.fmt("'%08b"').flip.comb }».Int;
}
method gist { <"| |>.join:{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" }
method succ {
self.new: :$!rule, :@!code, :cells(
self.code[
(4 X* @!cells.rotate(-1))code[
Z+ (2 X 4 «*« @!cells.rotate(-1)
Z»+« 2 «*« @!cells.rotate(1)
»+« 2 * @!cells[i] +.rotate(1)
]
)
Line 984 ⟶ 988:
 
my $size = 10;
 
my Automaton $a .= new:
:rule(30),
:cells( flat 0 xx $size, 1, 0 xx $size );
 
say $a++ for ^$size;</lang>
 
{{out}}
<pre>
<pre>| # |
| ### |
| ## # |
Line 998 ⟶ 1,006:
| ## #### ###### |
| ## # ### # |
| ## #### ## # ### |</pre>
</pre>
Unfortunately that version is somewhat slow due to the (as yet) unoptimized vector operations, as well as rebuilding the code every iteration. The following version runs about ten times faster and produces the same output:
<lang perl6>class Automaton {
has $.rule;
has @.cells;
has @.code;
 
method new (|args) { self.bless(|args).init }
method init { @!code ||= $!rule.fmt("%08b").flip.comb».Int; self; }
 
method gist { <| |>.join: @!cells.map({$_ ?? '#' !! ' '}).join }
method succ {
my \size = +@!cells;
self.new: :$!rule, :@!code, :cells(
@!code[
for ^size -> \i {
4 * @!cells[(i - 1) % size] +
2 * @!cells[i] +
@!cells[(i+1) % size];
}
]
);
}
}
 
my $size = 10;
my Automaton $a .= new:
:rule(30),
:cells( 0 xx $size, 1, 0 xx $size );
say $a++ for ^$size;</lang>
 
=={{header|Python}}==
Anonymous user