|
1 | 1 | <?php
|
2 |
| - |
| 2 | +$time_start = microtime(true); |
3 | 3 | $input = trim(file_get_contents('03.txt'));
|
4 | 4 |
|
5 |
| -$matches = []; |
6 |
| -preg_match_all('/mul\((\d{1,3}),(\d{1,3})\)/', $input, $matches); |
| 5 | +function op($in): int |
| 6 | +{ |
| 7 | + $matches = []; |
| 8 | + preg_match_all('/mul\((\d{1,3}),(\d{1,3})\)/', $in, $matches); |
| 9 | + $out = 0; |
| 10 | + for ($i = 0; $i < count($matches[0]); $i++) { |
| 11 | + $out += (int) $matches[1][$i] * (int) $matches[2][$i]; |
| 12 | + } |
| 13 | + return $out; |
| 14 | +} |
| 15 | + |
| 16 | +$pt1 = op($input); |
7 | 17 |
|
8 |
| -$pt1 = 0; |
9 |
| -for ($i = 0; $i < count($matches[0]); $i++) { |
10 |
| - $pt1 += $matches[1][$i] * $matches[2][$i]; |
| 18 | +// for part 2, we use the same regex but first do some string manipulation |
| 19 | +while (true) { |
| 20 | + $pos = strpos($input, "don't()"); |
| 21 | + if ($pos === false) { |
| 22 | + break; |
| 23 | + } |
| 24 | + |
| 25 | + $new = substr($input, 0, $pos); |
| 26 | + |
| 27 | + $next = strpos($input, "do()", $pos+1); |
| 28 | + if ($next !== false) { |
| 29 | + $new .= substr($input, $next); |
| 30 | + } |
| 31 | + $input = $new; |
11 | 32 | }
|
12 | 33 |
|
13 |
| -echo "Part 1: " , $pt1, PHP_EOL; |
| 34 | +$pt2 = op($input); |
| 35 | + |
| 36 | +echo "--- Day 3: Mull It Over ---", PHP_EOL; |
| 37 | +echo "Part 1: ", $pt1, PHP_EOL; |
| 38 | +echo "Part 2: ", $pt2, PHP_EOL; |
| 39 | +echo "Took ", (microtime(true) - $time_start) * 1000, " ms", PHP_EOL; |
| 40 | +echo PHP_EOL; |
0 commit comments