You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.3 KiB

2 weeks ago
<?php
final class Day3 extends Day {
function part1(): string {
$matches = [];
$input = implode("", $this->input);
preg_match_all("/mul\(([0-9]{1,3}),([0-9]{1,3})\)/", $input, $matches, PREG_SET_ORDER);
$sum = 0;
/** @var array<string> $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<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);
}
}