]> www.fi.muni.cz Git - aoc2020.git/blob - 21.pl
Task 9 Perl Golf-style
[aoc2020.git] / 21.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 my @seats = map { chomp; [ split // ] } (<>);
6
7 my $cols = @{ $seats[0] };
8 my $rows = @seats;
9
10 print "$cols x $rows\n";
11
12 while (1) {
13         my $was_change = 0;
14         my $occup = 0;
15         my @newseats;
16         for my $row (0 .. $rows-1) {
17                 my @newrow;
18                 for my $col (0 .. $cols-1) {
19                         my $neigh = '';
20                         for my $add ([-1, -1], [-1, 0], [-1, 1],
21                                 [0, -1], [0, 1],
22                                 [1, -1], [1, 0], [1, 1]) {
23                                 my $row1 = $row + $add->[0];
24                                 my $col1 = $col + $add->[1];
25                                 next if $row1 >= $rows || $row1 < 0
26                                         || $col1 >= $cols || $col1 < 0;
27                                 $neigh .= $seats[$row1]->[$col1];
28                         }
29                         my $neigh_empty =()= $neigh =~ /L/g;
30                         my $neigh_occup =()= $neigh =~ /#/g;
31
32                         if ($seats[$row]->[$col] eq 'L' && !$neigh_occup) {
33                                 push @newrow, '#';
34                                 $was_change = 1;
35                                 $occup++;
36                         } elsif ($seats[$row]->[$col] eq '#' && $neigh_occup >= 4) {
37                                 push @newrow, 'L';
38                                 $was_change = 1;
39                         } else {
40                                 push @newrow, $seats[$row]->[$col];
41                                 $occup++ if $seats[$row]->[$col] eq '#';
42                         }
43                 }
44                 push @newseats, \@newrow;
45         }
46         @seats = @newseats;
47         #for my $row (@seats) {
48         #       print @$row, "\n";
49         #}
50         print "$occup occupied seats\n";
51         # print "\n";
52         last if !$was_change;
53 }
54
55