| 1 | use v6-alpha; |
|---|
| 2 | |
|---|
| 3 | ## |
|---|
| 4 | # Script to output Wolfram-esque cellular automata |
|---|
| 5 | # |
|---|
| 6 | # usage: 'perl ca_wolfram.pl', followed by: |
|---|
| 7 | # -r rule_number (Specify in decimal, integer from 0 to 255) |
|---|
| 8 | # -s steps (Specify number of steps to display) |
|---|
| 9 | # -w width |
|---|
| 10 | # -i initial_state |
|---|
| 11 | # -t true_char |
|---|
| 12 | # -f false_char |
|---|
| 13 | ## |
|---|
| 14 | |
|---|
| 15 | use Getopt::Std; |
|---|
| 16 | my %opts = getopts( 'rswitf' ); |
|---|
| 17 | |
|---|
| 18 | ## |
|---|
| 19 | # options, with some reasonable defaults |
|---|
| 20 | my $rule_number = %opts<r> || 110; |
|---|
| 21 | my $steps = %opts<s> || 30; |
|---|
| 22 | my $width = %opts<w> || 30; |
|---|
| 23 | my $initial = %opts<i> || 'right'; |
|---|
| 24 | my $true_char = %opts<t> || 'x'; |
|---|
| 25 | my $false_char = %opts<f> || '.'; |
|---|
| 26 | |
|---|
| 27 | ## |
|---|
| 28 | # Single cell in the left, right, or middle for initial state |
|---|
| 29 | my $left = $steps; |
|---|
| 30 | my $right = $width + $steps - 1; |
|---|
| 31 | $width += ( $steps * 2 ); |
|---|
| 32 | my $middle = int( $width / 2 ); |
|---|
| 33 | |
|---|
| 34 | |
|---|
| 35 | ## |
|---|
| 36 | # Initialize and fill up the array with 0 |
|---|
| 37 | my Bool @line = 0 xx ($width-1); |
|---|
| 38 | |
|---|
| 39 | ## |
|---|
| 40 | # Set an initial state on the left, right, or middle |
|---|
| 41 | given $initial { |
|---|
| 42 | when 'left' { @line[$left] = 1 } |
|---|
| 43 | when 'right' { @line[$right] = 1 } |
|---|
| 44 | when 'middle' { @line[$middle] = 1 } |
|---|
| 45 | } |
|---|
| 46 | |
|---|
| 47 | ## |
|---|
| 48 | # Unpack the Wolfram rule number into a hash |
|---|
| 49 | |
|---|
| 50 | my Bool %rule_hash; |
|---|
| 51 | for ( 0 .. 7 ) -> $key { |
|---|
| 52 | %rule_hash{$key} = ?($rule_number +& (1 ~ 0 x $key) ); |
|---|
| 53 | } |
|---|
| 54 | |
|---|
| 55 | ## |
|---|
| 56 | # Print the rule hash, using shiny, new sprintf |
|---|
| 57 | say "Rule $rule_number:"; |
|---|
| 58 | for %rule_hash.keys -> $key { |
|---|
| 59 | say sprintf("%03b",$key) ~ " becomes " ~ +%rule_hash{$key}; |
|---|
| 60 | } |
|---|
| 61 | |
|---|
| 62 | ## |
|---|
| 63 | # Render the output on the screen. |
|---|
| 64 | my $beginprint = $steps; |
|---|
| 65 | my $endprint = @line.elems() - $steps; |
|---|
| 66 | |
|---|
| 67 | while ( $steps-- ) { |
|---|
| 68 | my $newline = (+<<@line[ $beginprint .. $endprint ]).join("") ; |
|---|
| 69 | $newline ~~ s:g/1/$true_char/; |
|---|
| 70 | $newline ~~ s:g/0/$false_char/; |
|---|
| 71 | say $newline; |
|---|
| 72 | |
|---|
| 73 | my @old_line = @line; |
|---|
| 74 | |
|---|
| 75 | for ( 0 .. $width - 3 ) -> $index { |
|---|
| 76 | my $index_key = :2((+<<@old_line[ $index .. $index + 2 ]).join("")); |
|---|
| 77 | @line[ $index + 1 ] = %rule_hash{$index_key}; |
|---|
| 78 | } |
|---|
| 79 | |
|---|
| 80 | } |
|---|