]> www.fi.muni.cz Git - aoc.git/blob - 2023/30.pl
Day 25: examining the input
[aoc.git] / 2023 / 30.pl
1 #!/usr/bin/perl -w
2
3 use v5.38;
4 use experimental 'for_list', 'builtin';
5 use builtin 'indexed';
6
7 chomp (my $line = <>);
8
9 sub hash {
10         $_ = shift;
11         my $n = 0;
12         for (split //) {
13                 $n += ord($_);
14                 $n *= 17;
15                 $n %= 256;
16         }
17         $n;
18 }
19
20 my @slot;
21
22 for (split /,/, $line) {
23         my ($name, $op, $num) = /(\w+)(\W)(\d*)/;
24         my $id = hash($name);
25         my $sl = $slot[$id];
26         if ($op eq '=') {
27                 my $found;
28                 for my $s (@$sl) {
29                         if ($s->[0] eq $name) {
30                                 $found = 1;
31                                 $s->[1] = $num;
32                         }
33                 }
34                 if (!$found) {
35                         push @$sl, [ $name, $num ];
36                 }
37         } elsif ($op eq '-') {
38                 @$sl = grep { $_->[0] ne $name } @{ $slot[$id] };
39         }
40 }
41
42 my $sum;
43 for my ($i, $s) (indexed @slot) {
44         for my ($j, $p) (indexed @$s) {
45                 $sum += ($i+1) * ($j+1) * $p->[1];
46         }
47 }
48 say $sum;
49