Advertisement
musifter

AoC 2022, day 14 (Perl - recursive)

Dec 14th, 2022
1,757
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.49 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. no warnings 'recursion';
  7.  
  8. use List::AllUtils   qw(max pairwise);
  9.  
  10. sub vec_sum  ($$) { return [pairwise {$a + $b}   @{$_[0]}, @{$_[1]}] }
  11. sub vec_step ($$) { return [pairwise {$b <=> $a} @{$_[0]}, @{$_[1]}] }
  12. sub point_eq ($$) { return ($_[0]->[0] == $_[1]->[0] and $_[0]->[1] == $_[1]->[1]) }
  13.  
  14. my %grid;
  15. my $maxY = 0;
  16.  
  17. # Read in rock structure:
  18. foreach (<>) {
  19.     my @corners = map { [split ','] } m#(\d+,\d+)#g;
  20.  
  21.     my $pos = shift @corners;
  22.     $grid{ $pos->[0], $pos->[1] } = '#';
  23.  
  24.     $maxY = max ($maxY, $pos->[1]);
  25.  
  26.     while (my $next = shift @corners) {
  27.         my $delta = vec_step( $pos, $next );
  28.  
  29.         do {
  30.             $pos = vec_sum( $pos, $delta );
  31.             $grid{ $pos->[0], $pos->[1] } = '#';
  32.         } until (point_eq( $pos, $next ));
  33.  
  34.         $maxY = max ($maxY, $pos->[1]);
  35.     }
  36. }
  37.  
  38. $maxY += 1;                         # add in space to infinite floor
  39.  
  40. my $part1;
  41. my $placed = 0;
  42.  
  43. sub recurse_fall {
  44.     my ($px,$py) = @_;
  45.     my $sand = 0;
  46.  
  47.     return (0) if ($py > $maxY);
  48.  
  49.     foreach my $fall ([0,1], [-1,1], [1,1]) {
  50.         my ($nx,$ny) = ($px + $fall->[0], $py + $fall->[1]);
  51.  
  52.         if (!$grid{$nx, $ny}) {         # place to fall
  53.             $sand += &recurse_fall( $nx, $ny );
  54.         }
  55.     }
  56.  
  57.     $grid{$px, $py} = 'o';
  58.     $part1 //= $placed if ($py == $maxY);
  59.     $placed++;
  60.  
  61.     return ($sand + 1);
  62. }
  63.  
  64. print "Part 2: ", &recurse_fall( 500, 0 ), "\n";
  65. print "Part 1: $part1\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement