Advertisement
musifter

AoC 2023 day 11 (Perl)

Dec 11th, 2023 (edited)
924
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.29 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use v5.26;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(all indexes true);
  7. use Math::Vector::Real;
  8.  
  9. # Read in grid
  10. my @Grid = map { chomp; [split(//)] } <>;
  11. my $Size = scalar( @Grid );                 # ASSUME: square grid
  12.  
  13. # Parse Grid: get blank rows, cols, and galaxies
  14. my @Galaxies;
  15. my @Blank_rows;
  16. my @Blank_cols;
  17. foreach my $i (0 .. $Size - 1) {
  18.     push (@Blank_rows, $i)  if (all { $_ eq '.' } $Grid[$i]->@*);
  19.     push (@Blank_cols, $i)  if (all { $_ eq '.' } map { $Grid[$_][$i] } (0 .. $Size - 1));
  20.  
  21.     push( @Galaxies, map { V($i,$_) } indexes { $_ eq '#' } $Grid[$i]->@* );
  22. }
  23.  
  24. sub expand_universe {
  25.     my $scale = $_[0] - 1;      # we already have the first lines
  26.  
  27.     my @shifted = map {
  28.                       my $g = $_;
  29.                       my $yshift = true { $g->[0] > $_ } @Blank_rows;
  30.                       my $xshift = true { $g->[1] > $_ } @Blank_cols;
  31.                       $g += V($yshift, $xshift) * $scale;
  32.                   } @Galaxies;
  33.  
  34.     my $dist = 0;
  35.     foreach my $i (0 .. $#shifted-1) {
  36.         foreach my $j ($i+1 .. $#shifted) {
  37.             $dist += $shifted[$i]->manhattan_dist( $shifted[$j] );
  38.         }
  39.     }
  40.  
  41.     return ($dist);
  42. }
  43.  
  44. say "Part 1: ", &expand_universe( 2 );
  45. say "Part 2: ", &expand_universe( 1_000_000 );
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement