Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- use strict;
- use warnings;
- use feature qw(say);
- use Math::Vector::Real;
- my ($vy,$vx) = Math::Vector::Real->canonical_base(2);
- my %Dirs = ('v' => $vy, '>' => $vx, '^' => -$vy, '<' => -$vx);
- $/ = '';
- my ($in_map, $in_moves) = map {[split /\n/]} <>;
- my @moves = map { split // } @$in_moves;
- my @Grid = map { [split //] } @$in_map;
- sub grid_at ($) { my $p = shift; return ($Grid[$p->[0]][$p->[1]]) }
- my $robot;
- foreach my $y (0 .. $in_map->$#*) {
- if ($in_map->[$y] =~ m#@#) {
- $robot = V($y, $-[0]);
- $Grid[$y][$-[0]] = '.';
- last;
- }
- }
- MOVE:
- foreach my $d (@moves) {
- my $move = $robot + $Dirs{$d};
- my $targ = grid_at($move);
- if ($targ ne 'O') {
- $robot = $move if ($targ eq '.'); # move
- next MOVE;
- }
- # Pushing a box
- my $end = $move;
- $end += $Dirs{$d} while (grid_at($end) eq 'O'); # multipush
- next MOVE if (grid_at($end) eq '#'); # bump
- # Put box at empty end, clear front of push, move robot to it.
- $Grid[ $end->[0] ][ $end->[1] ] = 'O';
- $Grid[ $move->[0] ][ $move->[1] ] = '.';
- $robot = $move;
- }
- my $part1 = 0;
- foreach my $y (0 .. $#Grid) {
- foreach my $x (0 .. $Grid[0]->$#*) {
- $part1 += (100 * $y + $x) if ($Grid[$y][$x] eq 'O');
- }
- }
- say "Part 1: $part1";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement