Advertisement
musifter

AoC 2024, day 2 (Perl)

Dec 1st, 2024 (edited)
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.80 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(all);
  8.  
  9. sub chain (&@) {
  10.     my $block = shift;
  11.     return (map { &$block( $_[$_-1], $_[$_] ) } (1 .. $#_));
  12. }
  13.  
  14. sub check_report (@) {
  15.     my @diffs = chain { $_[1] - $_[0] } @_;
  16.     return (all { 1 <= abs($_) <= 3 && ($diffs[0] * $_) > 0 } @diffs);
  17. }
  18.  
  19. my $part1 = 0;
  20. my $part2 = 0;
  21.  
  22. REPORT:
  23. foreach my $report (map { [m#(\d+)#g] } <>) {
  24.     if (&check_report( @$report )) {
  25.         $part1++;
  26.         next REPORT;
  27.     }
  28.  
  29.     for (my $i = 0; $i < @$report; $i++) {
  30.         my @new = @$report;
  31.         splice( @new, $i, 1 );
  32.  
  33.         if (&check_report( @new )) {
  34.             $part2++;
  35.             next REPORT;
  36.         }
  37.     }
  38. }
  39.  
  40. say "Part 1: ", $part1;
  41. say "Part 2: ", $part1 + $part2;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement