Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use List::Util qw(none any);
- my @Dirs = ([1,0], [0,1], [-1,0], [0,-1]);
- sub vec_sum ($$) { my ($v,$w) = @_; return (map {$v->[$_] + $w->[$_]} (0,1)) };
- $; = ',';
- my @DIM = (101, 103);
- # Robots is an array of arrays of two elements, 0 => position, 1 => velocity
- use constant POS => 0;
- use constant VEL => 1;
- my @robots = map { [map {[split(/,/, $_)]} m#([-0-9]+,[-0-9]+)#g] } <>;
- my $half = @robots / 2;
- TIME:
- for (my $time = 1; ; $time++) {
- my %grid;
- print ::stderr "Time: $time\r" if ($time % 500 == 0);
- foreach my $idx (0 .. $#robots) {
- my @pos = map { ($robots[ $idx ][ POS ][$_] + $robots[ $idx ][ VEL ][$_]) % $DIM[$_] } (0,1);
- $robots[ $idx ][ POS ] = \@pos;
- $grid{ $pos[0], $pos[1] }++;
- }
- # ASSUME: Just to speed it up, assuming no stacked robots at Christmas Tree.
- next TIME if (any {$_ > 1} values %grid);
- # ASSUME: Robots in Christmas Tree are all adjacent to someone, and since
- # "most of the robots should arrange themselves into a picture of a Christmas tree"
- # we'll look for the first case where half of them are and assume that's right.
- my $count = 0;
- foreach my $robot (@robots) {
- # ASSUME: Image of Christmas Tree does not wrap.
- $count++ if (none {$grid{ join($;, &vec_sum($robot->[POS], $_)) }} @Dirs);
- next TIME if ($count > $half);
- }
- print "TIME: $time ($count)\n";
- foreach my $y (0 .. $DIM[1] - 1) {
- print( $grid{$_,$y} // '.' ) foreach (0 .. $DIM[0] - 1);
- print "\n";
- }
- print "Part 2: $time\n";
- last;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement