swuecho
8/8/2012 - 2:40 AM

cell_automata.pl


sub deci_bin($n) {
    return $n if $n==0 || $n==1;
    my $k = $n div 2;
    my $b = $n % 2;
    my $E = deci_bin($k);
    return $E~$b;
}

sub automata($rule,$row) {
    my @keys="111","110","101","100","011","010","001","000";
    my @vals=substr(deci_bin($rule).comb.reverse.join ~'0'x 8,0,8).comb.reverse;
    my %rule= @keys Z, @vals;
    my @automata="0"x $row ~"1"~"0" x $row;
    #say @automata[*-1];
    for 1..$row {
	my $next='0';
	my $i=0;
	repeat while $i<=(@automata[*-1].chars)-3 {
	    my $str=substr(@automata[*-1],$i,3);
	    $next= $next ~ %rule{$str};
	    $i++;
    }  
    $next~='0';
    push @automata, $next;
  }
    @automata;
   
}


sub MAIN($rule,$row) {
for automata($rule, $row) { say $_.subst(rx/'0'/,' ',:g)}; # ; is not allowed after for
}