musifter

AoC 2021 day 5, part 2 (Perl)

Dec 5th, 2021 (edited)
499
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/perl
  2.  
  3. use utf8;
  4. use strict;
  5. use warnings;
  6. use v5.26;
  7.  
  8. use List::AllUtils  qw(pairwise all true);
  9. use Math::Utils     qw(sign);
  10.  
  11. sub vecsum (\@\@) {
  12.     my ($v1,$v2) = @_;
  13.     return (pairwise {$a + $b} @$v1, @$v2);
  14. }
  15.  
  16. sub veceq (\@\@) {
  17.     my ($v1,$v2) = @_;
  18.     return (all {$v1->[$_] == $v2->[$_]} (0 .. @$v1 - 1));
  19. }
  20.  
  21. my %grid;
  22. while (<>) {
  23.     my ($x1,$y1,$x2,$y2) = split /\D+/;
  24.  
  25.     my @Δ = sign($x2 - $x1, $y2 - $y1);
  26.     my @p = ($x1, $y1);
  27.     my @e = vecsum( @{[$x2,$y2]}, @Δ );
  28.  
  29.     until (veceq( @p, @e )) {
  30.         $grid{$p[0],$p[1]}++;
  31.         @p = vecsum( @p, @Δ );
  32.     }
  33. }
  34.  
  35. print "Part 2: ", (true {$grid{$_} >= 2} keys %grid), "\n";
RAW Paste Data