$mem_1 = $mem_2 = [];
foreach ($input->lines as $line) {
[$a, $b] = $line->split(" = ");
if ($a == "mask") {
$mask_0 = bindec($b->replace("X", 1));
$mask_1 = bindec($b->replace("X", 0));
$mask_x = bindec($b->replace("0", "1")->replace("X", "0"));
$pos_x = $b->chars->keep("X")->keys();
continue;
}
// Part 1
$pos = int($a->sub(4, -1));
$mem_1[$pos] = (int($b) & $mask_0) | $mask_1;
// Part 2
$pos = ($pos | $mask_1) & $mask_x;
$mem_2[$pos] = int($b);
foreach ($pos_x->combinations() as $cx) {
$m = 0;
foreach ($cx as $x) $m += 2 ** (35 - $x);
$mem_2[$pos | $m] = int($b);
}
}
$solution_1 = array_sum($mem_1);
$solution_2 = array_sum($mem_2);