parent
c1ff5f7242
commit
3a48ceea15
1 changed files with 58 additions and 0 deletions
@ -0,0 +1,58 @@ |
||||
<?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); |
||||
} |
||||
} |
Loading…
Reference in new issue