Skip to content

Commit c8a3b8f

Browse files
day 3 part 2
1 parent d67c87a commit c8a3b8f

File tree

3 files changed

+36
-9
lines changed

3 files changed

+36
-9
lines changed

2024-php/01.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,5 @@
3636
echo "--- Day 1: Historian Hysteria ---", PHP_EOL;
3737
echo "Part 1: ", $pt1, PHP_EOL;
3838
echo "Part 2: ", $pt2, PHP_EOL;
39-
echo "Took ", microtime(true) - $time_start, " seconds", PHP_EOL;
39+
echo "Took ", (microtime(true) - $time_start) * 1000, " ms", PHP_EOL;
4040
echo PHP_EOL;

2024-php/02.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,5 +51,5 @@ function is_safe(array $numbers): bool
5151
echo "--- Day 2: Red-Nosed Reports ---", PHP_EOL;
5252
echo "Part 1: ", $pt1, PHP_EOL;
5353
echo "Part 2: ", $pt2, PHP_EOL;
54-
echo "Took ", microtime(true) - $time_start, " seconds", PHP_EOL;
54+
echo "Took ", (microtime(true) - $time_start) * 1000, " ms", PHP_EOL;
5555
echo PHP_EOL;

2024-php/03.php

+34-7
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,40 @@
11
<?php
2-
2+
$time_start = microtime(true);
33
$input = trim(file_get_contents('03.txt'));
44

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);
717

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;
1132
}
1233

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

Comments
 (0)