2023-12-08 15:31:44 +00:00
|
|
|
use 5.38.0;
|
|
|
|
|
|
|
|
package Part1;
|
|
|
|
|
|
|
|
use List::AllUtils qw/ /;
|
|
|
|
|
2023-12-08 15:35:08 +00:00
|
|
|
sub parse_input ($input) {
|
2023-12-08 15:31:44 +00:00
|
|
|
my ( $directions, undef, @nodes ) = split "\n", $input;
|
|
|
|
|
|
|
|
$directions = [ split "", $directions =~ s/R/1/gr =~ s/L/0/gr ];
|
|
|
|
|
|
|
|
my %nodes;
|
|
|
|
|
2023-12-08 15:35:08 +00:00
|
|
|
for (@nodes) {
|
2023-12-08 15:52:54 +00:00
|
|
|
my @n = /([A-Z\d]+)/g;
|
2023-12-08 15:31:44 +00:00
|
|
|
$nodes{ shift @n } = \@n;
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
directions => $directions,
|
2023-12-08 15:35:08 +00:00
|
|
|
nodes => \%nodes
|
|
|
|
};
|
2023-12-08 15:31:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
sub solution_1 ($input) {
|
2023-12-08 15:35:08 +00:00
|
|
|
my $p = parse_input($input);
|
2023-12-08 15:31:44 +00:00
|
|
|
my @directions = $p->{directions}->@*;
|
2023-12-08 15:35:08 +00:00
|
|
|
my %nodes = $p->{nodes}->%*;
|
2023-12-08 15:31:44 +00:00
|
|
|
|
2023-12-08 15:35:08 +00:00
|
|
|
my $visited = 0;
|
2023-12-08 15:31:44 +00:00
|
|
|
my $next_index = 0;
|
2023-12-08 15:35:08 +00:00
|
|
|
my $current = 'AAA';
|
2023-12-08 15:31:44 +00:00
|
|
|
|
2023-12-08 15:35:08 +00:00
|
|
|
while ( $current ne 'ZZZ' ) {
|
2023-12-08 15:31:44 +00:00
|
|
|
$visited++;
|
|
|
|
|
2023-12-08 15:35:08 +00:00
|
|
|
$current =
|
|
|
|
$nodes{$current}->[ $directions[ $next_index++ % @directions ] ];
|
2023-12-08 15:31:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return $visited;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
1;
|