Advertisement
musifter

AoC 2022, day 9 (perl)

Dec 9th, 2022 (edited)
1,612
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.08 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::AllUtils  qw(max pairwise);
  7.  
  8. $; = ',';
  9.  
  10. my %dirs = ( 'R' => [0,1], 'L' => [0,-1], 'U' => [-1,0], 'D' => [1,0] );
  11.  
  12. sub vec_sum {
  13.     my ($v, $w) = @_;
  14.     return ([pairwise {$a + $b} @$v, @$w]);
  15. }
  16.  
  17. sub distance {
  18.     my ($h, $t) = @_;
  19.     return (max pairwise {abs($a - $b)} @$h, @$t);
  20. }
  21.  
  22. sub roach_move {
  23.     my ($h, $t) = @_;
  24.     return ([pairwise {$a <=> $b} @$h, @$t]);
  25. }
  26.  
  27. my @rope = map { [0,0] } (0 .. 9);
  28. my @trails = ({'0,0' => 1}, {'0,0' => 1});
  29.  
  30. while (<>) {
  31.     my ($dir, $steps) = m#^(\w) (\d+)#;
  32.  
  33.     foreach (1 .. $steps) {
  34.         $rope[0] = &vec_sum( $rope[0], $dirs{$dir} );
  35.  
  36.         foreach my $i (1 .. 9) {
  37.             if (&distance( $rope[$i-1], $rope[$i] ) > 1) {
  38.                 $rope[$i] = &vec_sum( $rope[$i], &roach_move( $rope[$i-1], $rope[$i] ) );
  39.             }
  40.         }
  41.  
  42.         $trails[0]{$rope[1][0],$rope[1][1]}++;
  43.         $trails[1]{$rope[9][0],$rope[9][1]}++;
  44.     }
  45. }
  46.  
  47. print "Part 1: ", scalar keys %{$trails[0]}, "\n";
  48. print "Part 2: ", scalar keys %{$trails[1]}, "\n";
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement