root/examples/ca_wolfram.pl

Revision 13101, 1.8 kB (checked in by rodi, 2 years ago)

Added printing of the rule set, using shiny new sprintf("%b,$str)

  • Property svn:executable set to *
Line 
1use 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
15use Getopt::Std;
16my %opts = getopts( 'rswitf' );
17
18##
19# options, with some reasonable defaults
20my $rule_number = %opts<r> || 110;
21my $steps       = %opts<s> || 30;
22my $width       = %opts<w> || 30;
23my $initial     = %opts<i> || 'right';
24my $true_char   = %opts<t> || 'x';
25my $false_char  = %opts<f> || '.';
26
27##
28# Single cell in the left, right, or middle for initial state
29my $left  = $steps;
30my $right = $width + $steps - 1;
31$width += ( $steps * 2 );
32my $middle = int( $width / 2 );
33
34
35##
36# Initialize and fill up the array with 0
37my Bool @line = 0 xx ($width-1);
38
39##
40# Set an initial state on the left, right, or middle
41given $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
50my Bool %rule_hash;
51for ( 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
57say "Rule $rule_number:";
58for %rule_hash.keys -> $key {
59    say sprintf("%03b",$key) ~ " becomes " ~ +%rule_hash{$key};
60}
61
62##
63# Render the output on the screen.
64my $beginprint = $steps;
65my $endprint   = @line.elems() - $steps;
66
67while ( $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}
Note: See TracBrowser for help on using the browser.