From 3a48ceea153892ed815db36b95daf73ec7968361 Mon Sep 17 00:00:00 2001 From: Benjamin Kraft Date: Sun, 5 Jan 2025 14:02:18 +0100 Subject: [PATCH] day 3 --- public/days/Day3.php | 58 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 public/days/Day3.php diff --git a/public/days/Day3.php b/public/days/Day3.php new file mode 100644 index 0000000..d7d677a --- /dev/null +++ b/public/days/Day3.php @@ -0,0 +1,58 @@ +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); + } +} \ No newline at end of file