]> www.fi.muni.cz Git - aoc2020.git/blob - 22.pl
Task 9 Perl Golf-style
[aoc2020.git] / 22.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 my @neighs;
13 for my $row (0 .. $rows-1) {
14         my @neigh_row;
15         for my $col (0 .. $cols-1) {
16                 my @neigh_seats;
17                 for my $add ([-1, -1], [-1, 0], [-1, 1],
18                         [0, -1], [0, 1],
19                         [1, -1], [1, 0], [1, 1]) {
20                         my ($row1, $col1) = ($row, $col);
21                         while (1) {
22                                 $row1 += $add->[0];
23                                 $col1 += $add->[1];
24                                 last if $row1 >= $rows || $row1 < 0
25                                         || $col1 >= $cols || $col1 < 0;
26                                 if ($seats[$row1]->[$col1] ne '.') {
27                                         push @neigh_seats, [$row1, $col1];
28                                         last;
29                                 }
30                         }
31                 }
32                 push @neigh_row, \@neigh_seats;
33         }
34         push @neighs, \@neigh_row;
35 }
36
37 while (1) {
38         my $was_change = 0;
39         my $occup = 0;
40         my @newseats;
41         for my $row (0 .. $rows-1) {
42                 my @newrow;
43                 for my $col (0 .. $cols-1) {
44                         my $neigh = '';
45                         for my $nl (@{ $neighs[$row]->[$col] }) {
46                                 $neigh .= $seats[$nl->[0]]->[$nl->[1]];
47                         }
48                         my $neigh_empty =()= $neigh =~ /L/g;
49                         my $neigh_occup =()= $neigh =~ /#/g;
50
51                         if ($seats[$row]->[$col] eq 'L' && !$neigh_occup) {
52                                 push @newrow, '#';
53                                 $was_change = 1;
54                                 $occup++;
55                         } elsif ($seats[$row]->[$col] eq '#' && $neigh_occup >= 5) {
56                                 push @newrow, 'L';
57                                 $was_change = 1;
58                         } else {
59                                 push @newrow, $seats[$row]->[$col];
60                                 $occup++ if $seats[$row]->[$col] eq '#';
61                         }
62                 }
63                 push @newseats, \@newrow;
64         }
65         @seats = @newseats;
66         # for my $row (@seats) {
67         #       print @$row, "\n";
68         # }
69         print "$occup occupied seats\n";
70         # print "\n";
71         last if !$was_change;
72 }
73
74