X-Git-Url: https://www.fi.muni.cz/~kas/git//home/kas/public_html/git/?a=blobdiff_plain;f=2023%2F30.pl;fp=2023%2F30.pl;h=8e813c625615e219c3183356dc2c6795f90c98ea;hb=f141c1ae1581135db4bc9f68aa677c7c499f4956;hp=0000000000000000000000000000000000000000;hpb=ab399e76f3712a096b87cd5a019c6981c3fde323;p=aoc.git diff --git a/2023/30.pl b/2023/30.pl new file mode 100755 index 0000000..8e813c6 --- /dev/null +++ b/2023/30.pl @@ -0,0 +1,49 @@ +#!/usr/bin/perl -w + +use v5.38; +use experimental 'for_list', 'builtin'; +use builtin 'indexed'; + +chomp (my $line = <>); + +sub hash { + $_ = shift; + my $n = 0; + for (split //) { + $n += ord($_); + $n *= 17; + $n %= 256; + } + $n; +} + +my @slot; + +for (split /,/, $line) { + my ($name, $op, $num) = /(\w+)(\W)(\d*)/; + my $id = hash($name); + my $sl = $slot[$id]; + if ($op eq '=') { + my $found; + for my $s (@$sl) { + if ($s->[0] eq $name) { + $found = 1; + $s->[1] = $num; + } + } + if (!$found) { + push @$sl, [ $name, $num ]; + } + } elsif ($op eq '-') { + @$sl = grep { $_->[0] ne $name } @{ $slot[$id] }; + } +} + +my $sum; +for my ($i, $s) (indexed @slot) { + for my ($j, $p) (indexed @$s) { + $sum += ($i+1) * ($j+1) * $p->[1]; + } +} +say $sum; +