input); preg_match_all("/mul\(([0-9]{1,3}),([0-9]{1,3})\)/", $input, $matches, PREG_SET_ORDER); $sum = 0; /** @var array $match */ foreach ($matches as $match) { $factor1 = intval($match[1]); $factor2 = intval($match[2]); $sum += $factor1 * $factor2; } return intval($sum); } function part2(): string { $input = implode("", $this->input); $mulMatches = []; preg_match_all("/mul\(([0-9]{1,3}),([0-9]{1,3})\)/", $input, $mulMatches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); $doMatches = []; preg_match_all("/do\(\)|don't\(\)/", $input, $doMatches, PREG_OFFSET_CAPTURE); $doMatches = $doMatches[0]; $sum = 0; $enabled = true; $nextDoInstructionIndex = 0; /** @var array $match */ foreach ($mulMatches as $match) { $position = intval($match[0][1]); $nextDoInstruction = $doMatches[$nextDoInstructionIndex] ?? null; if ($nextDoInstruction && $position > $nextDoInstruction[1]){ $enabled = $nextDoInstruction[0] === 'do()'; $nextDoInstructionIndex++; } if ($enabled){ $factor1 = intval($match[1][0]); $factor2 = intval($match[2][0]); $sum += $factor1 * $factor2; } } return intval($sum); } }