Answer ⏱ 5ms
Part 1 :
509784
Part 2 :
230197
function num($string) {
foreach (str_split($string) as $c) $sum = (($sum??0) + ord($c)) * 17 % 256;
return $sum;
}
// ==================================================
// > PART 1
// ==================================================
$solution_1 = array_sum(array_map("num", explode(",", $input)));
// ==================================================
// > PART 2
// ==================================================
$boxes = [];
foreach (explode(",", $input) as $step) {
preg_match("/([a-z]+)(=|-)([0-9]?)/", $step, $m);
[$_, $label, $sign, $fl] = $m;
$box = num($label);
if ($sign == "-") {
unset($boxes[$box][$label]);
} else {
$boxes[$box][$label] = $fl;
}
}
$solution_2 = 0;
foreach ($boxes as $i=>$box) {
$l = 1;
foreach ($box as $label=>$fl) $solution_2 += ($i + 1) * $l++ * $fl;
}