Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use Clone qw(clone);
- $; = ',';
- my %Grid;
- sub init_grid {
- my $dim;
- my $y = 0;
- while (<>) {
- chomp;
- $dim = length $_;
- my $x = 0;
- foreach my $cell (split //) {
- $Grid{0,0,$y,$x} = ($cell eq '#') ? 1 : 0;
- $x++;
- }
- $y++;
- }
- for my $w (-1 .. 1) {
- for my $z (-1 .. 1) {
- for my $y (-1 .. $dim) {
- for my $x (-1 .. $dim) {
- $Grid{$w,$z,$y,$x} //= 0;
- }
- }
- }
- }
- }
- #
- # Mainline
- #
- &init_grid();
- for my $time (1 .. 6) {
- my %next;
- my $live = 0;
- print "Time: $time; ";
- foreach my $coord (keys %Grid) {
- my ($cw, $cz, $cy, $cx) = split( /,/, $coord );
- # count neighbours (including self)
- my $neigh = 0;
- foreach my $w ($cw - 1 .. $cw + 1) {
- foreach my $z ($cz - 1 .. $cz + 1) {
- foreach my $y ($cy - 1 .. $cy + 1) {
- foreach my $x ($cx - 1 .. $cx + 1) {
- $neigh++ if ($Grid{$w,$z,$y,$x});
- }
- }
- }
- }
- # check live (remember to add one to self-live checks
- if ($Grid{$coord}) {
- $next{$coord} = ($neigh == 3 || $neigh == 4) ? 1 : 0;
- } else {
- $next{$coord} = ($neigh == 3) ? 1 : 0;
- }
- # count live cells and make neighbours exist to check next time
- if ($next{$coord}) {
- $live++;
- foreach my $w ($cw - 1 .. $cw + 1) {
- foreach my $z ($cz - 1 .. $cz + 1) {
- foreach my $y ($cy - 1 .. $cy + 1) {
- foreach my $x ($cx - 1 .. $cx + 1) {
- $next{$w,$z,$y,$x} //= 0;
- }
- }
- }
- }
- }
- }
- print "live: $live\n";
- %Grid = %{clone(\%next)};
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement