sub show(@cave, $x-min, $x-max, $y-max) {
for 0..$y-max -> \y0 {
for $x-min..$x-max -> \x0 {
print @cave[y0;x0] // '.';
}
put '';
}
}
my @cave;
my ($x-min, $x-max, $y-max) = ∞, 0, 0;
for $*IN.lines».comb(/\d+/)».Int -> @coords {
for ^(+@coords/2-1) -> \j {
for (@coords[2*j]...@coords[2*j+2]) X (@coords[2*j+1]...@coords[2*j+3]) -> (\x0, \y0) {
@cave[y0;x0] = '#';
$x-min = x0 if x0 < $x-min;
$x-max = x0 if x0 > $x-max;
$y-max = y0 if y0 > $y-max;
}
}
}
@cave[$y-max+2;$_] = '#' for 500-$y-max-2 .. 500+$y-max+2;
$y-max += 2;
$x-min = 500 - $y-max;
$x-max = 500 + $y-max;
my $cnt = 0;
while !@cave[0;500].defined {
my $x1 = 500;
my $y1 = 0;
my Bool $cannot-move = False;
repeat {
if !@cave[$y1+1;$x1].defined {
++$y1;
} elsif !@cave[$y1+1;$x1-1].defined {
--$x1; ++$y1;
} elsif !@cave[$y1+1;$x1+1].defined {
++$x1; ++$y1;
} else {
$cannot-move = True;
}
} until $cannot-move;
@cave[$y1;$x1] = 'o';
++$cnt;
}
show(@cave, $x-min, $x-max, $y-max);
put "part 2: ", $cnt;