Advertisement
musifter

AoC 2021 day 25 (Perl -- messy but quick)

Dec 25th, 2021
2,418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.31 KB | None | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. $| = 1;
  7.  
  8. my @Grid = map { chomp; [map {($_ eq '.') ? 0 :
  9.                               ($_ eq '>') ? 1 : 2} split //] } <>;
  10.  
  11. my $Y_SIZE = @Grid;
  12. my $X_SIZE = $Grid[0]->@*;
  13.  
  14. my $moved;
  15. my $time = 0;
  16.  
  17. do {
  18.     $moved = 0;
  19.  
  20.     my @new_grid = ();
  21.     for (my $y = 0; $y < $Y_SIZE; $y++) {
  22.         my $ahead = $Grid[$y][0];
  23.         for (my $x = $X_SIZE - 1; $x >= 0; $x--) {
  24.             if (!$ahead and $Grid[$y][$x] == 1) {
  25.                 $new_grid[$y][($x + 1) % $X_SIZE] = 1;
  26.                 $new_grid[$y][$x] = 0;
  27.                 $moved++;
  28.             }
  29.  
  30.             $ahead = $Grid[$y][$x];
  31.             $new_grid[$y][$x] //= $ahead;
  32.         }
  33.     }
  34.  
  35.     @Grid = @new_grid;
  36.  
  37.     @new_grid = ();
  38.     for (my $x = 0; $x < $X_SIZE; $x++) {
  39.         my $ahead = $Grid[0][$x];
  40.         for (my $y = $Y_SIZE - 1; $y >= 0; $y--) {
  41.             if (!$ahead and $Grid[$y][$x] == 2) {
  42.                 $new_grid[($y + 1) % $Y_SIZE][$x] = 2;
  43.                 $new_grid[$y][$x] = 0;
  44.                 $moved++;
  45.             }
  46.  
  47.             $ahead = $Grid[$y][$x];
  48.             $new_grid[$y][$x] //= $ahead;
  49.         }
  50.     }
  51.  
  52.     @Grid = @new_grid;
  53.  
  54.     print ::stderr "Time: ", ++$time, "  moved: $moved    \r";
  55. } until (not $moved);
  56.  
  57. print "\nPart 1: $time\n";
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement