my method hash(Str:D $s : --> UInt:D) {
(0, |$s.comb).reduce({ ($^a + $^b.ord) * 17 % 256 })
}
my $input = $*IN.slurp;
put 'part 1: ', $input.split(',')».&hash.sum;
my $rgx = rx/^ (<[a..z]>+) ('='|'-') (\d)? $/;
my @boxes = [] xx 256;
for $input.split(',') -> $ins {
my ($label, $action, $focus) = $ins.match($rgx).map(~*);
given @boxes[$label.&hash] -> $box {
given $action {
when '=' {
with $box.first(*[0] eq $label, :k) {
$box[$_;1] = $focus;
} else {
$box.push([$label, $focus]);
}
}
when '-' {
$box.splice($_, 1) with $box.first(*[0] eq $label, :k);
}
}
}
}
put 'part 2: ', @boxes.pairs.map({ (.key+1) * .value.pairs.map({ (.key+1) * .value[1] }).sum }).sum;