sol1.pl (1711B) [raw]
1 #!/usr/bin/env perl 2 use strict; 3 use warnings; 4 5 use Storable qw(dclone); 6 7 # Read in the grid 8 # TRICK: to make neighbors easier, pad by '.' on all ends 9 my @G; 10 my $i = 0; 11 while (<ARGV>) { 12 chomp; 13 $G[$i] = ['.', split('', $_), '.']; 14 $i++; 15 } 16 push(@G, [('.') x scalar @{$G[0]}]); 17 unshift(@G, [('.') x scalar @{$G[0]}]); 18 19 $i = 0; 20 while (evolve(\@G)) { 21 print "Evolving ... $i\n"; 22 $i++; 23 } 24 25 my $total = 0; 26 for my $r (@G) { 27 $total += scalar grep { $_ eq '#' } @$r; 28 } 29 print "$total\n"; 30 31 sub evolve { 32 my ($G) = @_; 33 # 1. deep clone 34 # 2. for loop over grid, change (mark did_change) 35 # 3. return did_change 36 my $orig = dclone($G); 37 my $did_change; 38 39 my $R = scalar @$orig; 40 my $C = scalar @{$orig->[0]}; 41 for (my $i = 1; $i < $R - 1; $i++) { 42 for (my $j = 1; $j < $C - 1; $j++) { 43 my $seat = $orig->[$i]->[$j]; 44 next if $seat eq '.'; # floor don't change 45 46 # neighbors... 47 my @neighs = map { $orig->[$_->[0]]->[$_->[1]] } ( 48 [$i - 1, $j - 1], 49 [$i - 1, $j], 50 [$i - 1, $j + 1], 51 [$i, $j - 1], 52 #[$i, $j], <-- don't include self 53 [$i, $j + 1], 54 [$i + 1, $j - 1], 55 [$i + 1, $j], 56 [$i + 1, $j + 1], 57 ); 58 my $num_occ = scalar grep { $_ eq '#' } @neighs; 59 60 if ($seat eq 'L' && $num_occ == 0) { 61 $G->[$i]->[$j] = '#'; 62 $did_change = 1; 63 } elsif ($seat eq '#' && $num_occ >= 4) { 64 $G->[$i]->[$j] = 'L'; 65 $did_change = 1; 66 } 67 } 68 } 69 70 return $did_change;; 71 }