Advertisement
musifter

AoC 2024, day 14, part 2 (Perl)

Dec 14th, 2024
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.64 KB | Source Code | 0 0
  1. #!/usr/bin/perl
  2.  
  3. use strict;
  4. use warnings;
  5.  
  6. use List::Util      qw(none any);
  7.  
  8. my @Dirs = ([1,0], [0,1], [-1,0], [0,-1]);
  9.  
  10. sub vec_sum ($$) { my ($v,$w) = @_; return (map {$v->[$_] + $w->[$_]} (0,1)) };
  11.  
  12. $; = ',';
  13. my @DIM = (101, 103);
  14.  
  15. # Robots is an array of arrays of two elements, 0 => position, 1 => velocity
  16. use constant  POS => 0;
  17. use constant  VEL => 1;
  18.  
  19. my @robots = map { [map {[split(/,/, $_)]} m#([-0-9]+,[-0-9]+)#g] } <>;
  20. my $half = @robots / 2;
  21.  
  22. TIME:
  23. for (my $time = 1; ; $time++) {
  24.     my %grid;
  25.  
  26.     print ::stderr "Time: $time\r"  if ($time % 500 == 0);
  27.  
  28.     foreach my $idx (0 .. $#robots) {
  29.         my @pos = map { ($robots[ $idx ][ POS ][$_] + $robots[ $idx ][ VEL ][$_]) % $DIM[$_] } (0,1);
  30.  
  31.         $robots[ $idx ][ POS ] = \@pos;
  32.         $grid{ $pos[0], $pos[1] }++;
  33.     }
  34.  
  35.     # ASSUME: Just to speed it up, assuming no stacked robots at Christmas Tree.
  36.     next TIME if (any {$_ > 1} values %grid);
  37.  
  38.     # ASSUME: Robots in Christmas Tree are all adjacent to someone, and since
  39.     # "most of the robots should arrange themselves into a picture of a Christmas tree"
  40.     # we'll look for the first case where half of them are and assume that's right.
  41.     my $count = 0;
  42.     foreach my $robot (@robots) {
  43.         # ASSUME: Image of Christmas Tree does not wrap.
  44.         $count++ if (none {$grid{ join($;, &vec_sum($robot->[POS], $_)) }} @Dirs);
  45.         next TIME if ($count > $half);
  46.     }
  47.  
  48.     print "TIME: $time ($count)\n";
  49.     foreach my $y (0 .. $DIM[1] - 1) {
  50.         print( $grid{$_,$y} // '.' )  foreach (0 .. $DIM[0] - 1);
  51.         print "\n";
  52.     }
  53.  
  54.     print "Part 2: $time\n";
  55.     last;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement