musifter

AoC 2025, day 6 part 2 (Perl)

Dec 6th, 2025 (edited)
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.88 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::Util      qw(sum product zip);
  8.  
  9. sub chain (&@) {
  10.     my $block = shift;
  11.     return (map { &$block( $_[$_-1], $_[$_] ) } (1 .. $#_));
  12. }
  13.  
  14. # Read input:
  15. my @input = <>;
  16. my @ops   = map { split /\s+/ } pop @input;
  17.  
  18. # Find space delimiters (those shared by all lines)
  19. my %spaces;
  20. foreach (@input) {
  21.     $spaces{pos($_)}++ while (m/\s/g);
  22. }
  23.  
  24. my @spaces = sort {$a<=>$b} grep { $spaces{$_} == @input } keys %spaces;
  25.  
  26. # Do calculation:
  27. my $part2 = 0;
  28. foreach my $width (chain {$_[1] - $_[0]} (0, @spaces)) {
  29.     # Grab next numbers with the trailing space delimiter
  30.     my @horz = map { [split //, substr( $_, 0, $width, '' )] } @input;
  31.     my @vert = grep { m#\d# } map { join( '', @$_ ) } zip @horz;
  32.  
  33.     $part2 += (shift @ops eq '+') ? sum @vert : product @vert;
  34. }
  35.  
  36. say "Part 2: $part2";
Advertisement
Add Comment
Please, Sign In to add comment