Advertisement
musifter

AoC 2022 day 15 (perl pt1)

Dec 15th, 2022 (edited)
1,584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.22 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(min max);
  7.  
  8. sub in_range {
  9.     my ($pt, $range) = @_;
  10.     return ($range->[0] <= $pt <= $range->[1]);
  11. }
  12.  
  13. sub try_merge {
  14.     my ($p, $q) = @_;
  15.  
  16.     if (($q->[1] - $p->[0]) * ($q->[0] - $p->[1]) <= 0) {
  17.         return ([min ($p->[0], $q->[0]), max ($p->[1], $q->[1])]);
  18.     }
  19.  
  20.     return (0);
  21. }
  22.  
  23. my $row = 2_000_000;
  24. my @ranges;
  25. my %beacons;
  26.  
  27. foreach my $line (<>) {
  28.     my ($x, $y, $bx, $by) = ($line =~ m#(-?\d+)#g);
  29.  
  30.     if ($by == $row) {
  31.         $beacons{ $bx }++;
  32.     }
  33.  
  34.     my $dist = abs( $x - $bx ) + abs( $y - $by );
  35.     my $to_row = abs( $y - $row );
  36.  
  37.     my $diff = $dist - $to_row;
  38.  
  39.     if ($diff >= 0) {
  40.         push( @ranges, [$x - $diff, $x + $diff] );
  41.     }
  42. }
  43.  
  44. @ranges = sort { $a->[0] <=> $b->[0] } @ranges;
  45.  
  46. my @new = (shift @ranges);
  47. foreach my $range (@ranges) {
  48.     my $merge = &try_merge( $new[-1], $range );
  49.     if ($merge == 0) {
  50.         push( @new, $range );
  51.     } else {
  52.         $new[-1] = $merge;
  53.     }
  54. }
  55.  
  56. my $part1 = 0;
  57. foreach my $r (@new) {
  58.     $part1 += $r->[1] - $r->[0] + 1;
  59.     foreach my $b (keys %beacons) {
  60.         $part1-- if (&in_range( $b, $r ));
  61.     }
  62. }
  63.  
  64. print "Part 1: $part1\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement