Advertisement
musifter

AoC 2023 day 18, part 2 (Perl)

Dec 18th, 2023 (edited)
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 0.85 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use feature         qw(say);
  7.  
  8. use Math::Vector::Real;
  9. my ($Y,$X) = Math::Vector::Real->canonical_base(2);
  10. my @Dirs = ($X, $Y, -$X, -$Y);
  11.  
  12. my $pos = V(0,0);
  13. my @vertices = ($pos);
  14. my $trench = 0;
  15.  
  16. while (<>) {
  17.     my ($col) = m#[UDLR] \d+ (.*)#g;
  18.     my ($len, $dir) = ($col =~ m#([[:xdigit:]]{5})(\d)#g);
  19.  
  20.     $len = oct("0x$len");
  21.  
  22.     $trench += $len;
  23.     push( @vertices, $pos += $len * $Dirs[$dir] );
  24. }
  25.  
  26. # Shoelace for area (loop gives twice the area (sign +'ve widdershins, -'ve for deasil))
  27. my $area = 0;
  28. foreach my $i (0 .. $#vertices - 1) {
  29.     $area += $vertices[$i][0] * $vertices[$i+1][1];
  30.     $area -= $vertices[$i][1] * $vertices[$i+1][0];
  31. }
  32.  
  33. # Pick's formula: I+B = A + B/2 + 1 (but still needed to halve the Area from shoelace)
  34. say "Part 2: ", (abs($area) + $trench) / 2 + 1;
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement