Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use List::AllUtils qw(firstidx indexes reduce);
- sub hash ($) { reduce {(($a+$b)*17) % 256} (0, map {ord} split(//, shift)) };
- my @Boxes;
- my $part1 = 0;
- foreach (map {chomp; split /,/} <>) {
- my ($label, $op, $foc) = m#(\w+)([=-])(\d?)#;
- $part1 += hash $_;
- my $box = hash $label;
- # Look for label in box:
- my $idx = firstidx { $label eq $_->[0] } $Boxes[$box]->@*;
- if ($op eq '-') {
- splice( $Boxes[$box]->@*, $idx, 1 ) if ($idx != -1); # - remove lens
- } elsif ($idx != -1) {
- $Boxes[$box][$idx] = [$label, $foc]; # = replace lens
- } else {
- push( $Boxes[$box]->@*, [$label, $foc] ); # = add lens
- }
- }
- my $part2 = 0;
- foreach my $i (indexes {defined} @Boxes) {
- $part2 += ($i+1) * ($_+1) * $Boxes[$i][$_][1] foreach (0 .. $Boxes[$i]->$#*);
- }
- say "Part 1: ", $part1;
- say "Part 2: ", $part2;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement