#!/usr/bin/perl use v5.35.0; use List::Util 'sum'; # Parse input map my $width = 100; my (@wall, @goods, $start); my $size = 0; while (defined($_ = <>) && /./) { for ((split //), (' ') x ($width - length)) { $wall[$size] = +/[\s#]/; $goods[$size] = +/O/; $start = $size if /@/; $size++; } } # Walk around as directed my $robot = $start; while (<>) { for (split //) { my $dir = index '^>v<', $_; if ($dir >= 0) { my $step = (-$width, 1, $width, -1)[$dir]; my $pos = $robot + $step; $pos += $step while $goods[$pos]; unless ($wall[$pos]) { $robot += $step; $goods[$pos] = $goods[$robot]; $goods[$robot] = 0; } } } } # Deliver the goods say sum map {$goods[$_] && $_} (0 .. $#goods);