Advertisement
musifter

AoC 2022, day 13 (Perl)

Dec 13th, 2022 (edited)
1,368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.34 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(indexes none min product);
  7.  
  8. sub inc (@) {
  9.     return (map {$_ + 1} @_);
  10. }
  11.  
  12. #
  13. #  Packet comparison (recursive)
  14. #
  15. sub cmp_packet {
  16.     my @pack = @_;
  17.  
  18.     # Handle base case of two integers:
  19.     return ($pack[0] <=> $pack[1])  if (none { ref } @pack);
  20.  
  21.     # List comparisons (first promote if needed)
  22.     @pack = map { !ref ? [$_] : $_ } @pack;
  23.  
  24.     # Try elements up to size of smaller list:
  25.     my $minlen = min map { scalar @$_ } @pack;
  26.  
  27.     for (my $i = 0; $i < $minlen; $i++) {
  28.         my $ret = &cmp_packet( $pack[0][$i], $pack[1][$i] );
  29.         return ($ret)  if ($ret != 0);
  30.     }
  31.  
  32.     # Finally, compare sizes of lists:
  33.     return ($pack[0]->@* <=> $pack[1]->@*);
  34. }
  35.  
  36. #
  37. #  Part 1
  38. #
  39. my @input = map {$_ ? eval($_) : undef} <>;
  40.  
  41. my $part1 = 0;
  42. for (my $i = 1; $i <= @input / 2; $i++) {
  43.     my $left  = $input[2*$i - 2];
  44.     my $right = $input[2*$i - 1];
  45.  
  46.     $part1 += $i  if (&cmp_packet( $left, $right ) < 0);
  47. }
  48.  
  49. print "Part 1: $part1\n";
  50.  
  51. #
  52. # Part 2
  53. #
  54. my @markers = ([[2]], [[6]]);
  55. push( @input, @markers );
  56.  
  57. my $part2 = product inc indexes {
  58.                             my $packet = $_;
  59.                             grep { $_ == $packet } @markers
  60.                         } sort {&cmp_packet( $a, $b )} @input;
  61.  
  62. print "Part 2: $part2\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement