Elementary cellular automaton: Difference between revisions

From Rosetta Code
Content added Content deleted
m (correction)
m (→‎{{header|Perl 6}}: Automat**on**)
Line 15: Line 15:
=={{header|Perl 6}}==
=={{header|Perl 6}}==


<lang perl6>class Automata {
<lang perl6>class Automaton {
has ($.rule, @.cells);
has ($.rule, @.cells);
method gist { <| |>.join: @!cells.map({$_ ?? '#' !! ' '}).join }
method gist { <| |>.join: @!cells.map({$_ ?? '#' !! ' '}).join }
Line 31: Line 31:


my $size = 10;
my $size = 10;
my Automata $a .= new:
my Automaton $a .= new:
:rule(30),
:rule(30),
:cells( 0 xx $size, 1, 0 xx $size );
:cells( 0 xx $size, 1, 0 xx $size );

Revision as of 17:17, 27 February 2014

Elementary cellular automaton is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

An elementary cellular automaton is a one-dimensional cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.

The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.

The purpose of this task is to create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automata of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.

You can either produce an ASCII rendering of the state evolution or a PBM image.

You can deal with the limit conditions (what happens on the borders of the space) in any way you please.

This task is basically a generalization of one-dimensional cellular automaton.

Perl 6

<lang perl6>class Automaton {

   has ($.rule, @.cells);
   method gist { <| |>.join: @!cells.map({$_ ?? '#' !! ' '}).join }
   method code { $.rule.fmt("%08b").flip.comb }
   method succ {

self.new: :$.rule, :cells( self.code[ 4 «*« @.cells.rotate(-1) Z+ 2 «*« @.cells Z+ @.cells.rotate(1) ] )

   }

}

my $size = 10; my Automaton $a .= new:

   :rule(30),
   :cells( 0 xx $size, 1, 0 xx $size );

say $a++ for ^$size;</lang>

Output:
|          #          |
|         ###         |
|        ##  #        |
|       ## ####       |
|      ##  #   #      |
|     ## #### ###     |
|    ##  #    #  #    |
|   ## ####  ######   |
|  ##  #   ###     #  |
| ## #### ##  #   ### |