How to resolve the algorithm Elementary cellular automaton step by step in the Perl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Elementary cellular automaton step by step in the Perl programming language

Table of Contents

Problem Statement

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.

Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should wrap: this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of one-dimensional cellular automata.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Elementary cellular automaton step by step in the Perl programming language

Source code in the perl programming language

use strict;
use warnings;

package Automaton {
    sub new {
	my $class = shift;
	my $rule = [ reverse split //, sprintf "%08b", shift ];
	return bless { rule => $rule, cells => [ @_ ] }, $class;
    }
    sub next {
	my $this = shift;
	my @previous = @{$this->{cells}};
	$this->{cells} = [
	    @{$this->{rule}}[
	    map {
	      4*$previous[($_ - 1) % @previous]
	    + 2*$previous[$_]
	    +   $previous[($_ + 1) % @previous]
	    } 0 .. @previous - 1
	    ]
	];
	return $this;
    }
    use overload
    q{""} => sub {
	my $this = shift;
	join '', map { $_ ? '#' : ' ' } @{$this->{cells}}
    };
}

my @a = map 0, 1 .. 91; $a[45] = 1;
my $a = Automaton->new(90, @a);

for (1..40) {
    print "|$a|\n"; $a->next;
}


  

You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Crystal programming language
You may also check:How to resolve the algorithm Fermat numbers step by step in the C programming language
You may also check:How to resolve the algorithm Tonelli-Shanks algorithm step by step in the Phix programming language
You may also check:How to resolve the algorithm User input/Text step by step in the Lasso programming language
You may also check:How to resolve the algorithm Bitwise IO step by step in the Seed7 programming language