Advertisement
musifter

AoC 2024, day 14, part 2 stats (Perl)

Dec 14th, 2024
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.04 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 List::Util          qw(max);
  9. use Statistics::Basic   qw(variance);
  10. use ntheory             qw(invmod);
  11.  
  12. use constant  X => 0;
  13. use constant  Y => 1;
  14.  
  15. my @DIM = (101, 103);
  16.  
  17. # Robots is an array of arrays of two elements, 0 => position, 1 => velocity
  18. use constant  POS => 0;
  19. use constant  VEL => 1;
  20.  
  21. my @robots = map { [map {[split(/,/, $_)]} m#([-0-9]+,[-0-9]+)#g] } <>;
  22.  
  23. my ($minX, $varX, $minY, $varY) = (-1, ~0, -1, ~0);
  24.  
  25. for (my $time = 1; $time <= max @DIM; $time++) {
  26.     foreach my $i (0 .. $#robots) {
  27.         $robots[$i][POS] = [map {($robots[$i][POS][$_] + $robots[$i][VEL][$_]) % $DIM[$_]} (X,Y)];
  28.     }
  29.  
  30.     my $vx = variance map {$_->[POS][X]} @robots;
  31.     my $vy = variance map {$_->[POS][Y]} @robots;
  32.  
  33.     ($minX, $varX) = ($time, $vx) if ($vx < $varX);
  34.     ($minY, $varY) = ($time, $vy) if ($vy < $varY);
  35. }
  36.  
  37. say "[$minX] $varX";
  38. say "[$minY] $varY";
  39.  
  40. say "Part 2: ", $minX + ((invmod($DIM[X], $DIM[Y]) * ($minY - $minX)) % $DIM[Y]) * $DIM[X];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement