Advertisement
musifter

AoC 2023 day 15 (Perl)

Dec 15th, 2023 (edited)
893
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.97 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7. use List::AllUtils  qw(firstidx indexes reduce);
  8.  
  9. sub hash ($) { reduce {(($a+$b)*17) % 256} (0, map {ord} split(//, shift)) };
  10.  
  11. my @Boxes;
  12. my $part1 = 0;
  13. foreach (map {chomp; split /,/} <>) {
  14.     my ($label, $op, $foc) = m#(\w+)([=-])(\d?)#;
  15.  
  16.     $part1 += hash $_;
  17.     my $box = hash $label;
  18.  
  19.     # Look for label in box:
  20.     my $idx = firstidx { $label eq $_->[0] } $Boxes[$box]->@*;
  21.  
  22.     if ($op eq '-') {
  23.         splice( $Boxes[$box]->@*, $idx, 1 )  if ($idx != -1);   # - remove lens
  24.     } elsif ($idx != -1) {
  25.         $Boxes[$box][$idx] = [$label, $foc];                    # = replace lens
  26.     } else {
  27.         push( $Boxes[$box]->@*, [$label, $foc] );               # = add lens
  28.     }
  29. }
  30.  
  31. my $part2 = 0;
  32. foreach my $i (indexes {defined} @Boxes) {
  33.     $part2 += ($i+1) * ($_+1) * $Boxes[$i][$_][1] foreach (0 .. $Boxes[$i]->$#*);
  34. }
  35.  
  36. say "Part 1: ", $part1;
  37. say "Part 2: ", $part2;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement