Day 8 part 1 gives us a directed graph of nodes with links to two (hopefully other) nodes and a set of dance moves to perform through the graph; how many steps to get from AAA
to ZZZ
at the end of a dance pattern? (A lot more steps if you stray into DDD
, EEE
, or GGG
.)
RL
AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)
All one need do is make a hash of the nodes with their branches, then dance through it.
my %index = ( L => 0, R => 1 );
The dance moves are specified as L
or R and for no particular reason I decided to save the branches as arrays instead of hashes, so I prepare to translate dance moves into array indices. Why on earth did I call this %index
instead of %dirindex
or %dir
? Because I had just woken up and it was time to do AoC? Probably.
$_ = <>; chomp;
my @instr = map { $index{$_} } split(//);
<>;
I grab the dance moves, translate them from directions to indices, and toss the following blank line.
my %map;
while (<>) {
my ($node, $l, $r) = /(\w{3})/g;
$map{$node} = [ $l, $r ];
}
Then read in and save all the nodes.
my $count = 0;
my $pos = "AAA";
until ($count % @instr == 0 && $pos eq "ZZZ") {
$pos = $map{$pos}[$instr[$count++ % @instr]];
}
Finally, start at AAA
; take steps, counting as I go (and using the modulus of the number of dance moves in the pattern); and stop at ZZZ
only if it's the end of this dance pattern.
Full Program
#!/usr/bin/perl
use warnings;
use strict;
my %index = ( L => 0, R => 1 );
$_ = <>; chomp;
my @instr = map { $index{$_} } split(//);
<>;
my %map;
while (<>) {
my ($node, $l, $r) = /(\w{3})/g;
$map{$node} = [ $l, $r ];
}
my $count = 0;
my $pos = "AAA";
until ($count % @instr == 0 && $pos eq "ZZZ") {
$pos = $map{$pos}[$instr[$count++ % @instr]];
}
print "$count steps\n";