Skip to content

Commit a0c246d

Browse files
committed
2024.05
1 parent a0c24a4 commit a0c246d

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

php/2024/05/01.php

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
<?php
2+
3+
$start = microtime(true);
4+
5+
6+
#$file = file_get_contents('example.txt');
7+
$file = file_get_contents('input.txt');
8+
9+
$sum1 = $sum2 = 0;
10+
11+
[$rawChecks, $rawPages] = explode("\n\n", $file);
12+
$rawChecks = explode("\n", $rawChecks);
13+
$rawPages = explode("\n", $rawPages);
14+
15+
$checks = $manuals = [];
16+
foreach ($rawChecks as $check) {
17+
$checks[] = explode("|", $check);
18+
}
19+
foreach ($rawPages as $pageList) {
20+
$manuals[] = explode(",", $pageList);
21+
}
22+
23+
function isValid(array $pages, array $checks): bool
24+
{
25+
foreach ($checks as $check) {
26+
// find pos of both numbers
27+
$leftPos = array_search($check[0], $pages);
28+
$rightPos = array_search($check[1], $pages);
29+
30+
// if pos of right number is before the left, abort
31+
if ($leftPos === false || $rightPos === false) {
32+
continue;
33+
}
34+
if ($leftPos > $rightPos) {
35+
return false;
36+
}
37+
}
38+
return true;
39+
}
40+
41+
$invalidManuals = [];
42+
foreach ($manuals as $pages) {
43+
if (isValid($pages, $checks)) {
44+
$sum1 += $pages[(count($pages)-1)/2];
45+
} else {
46+
$invalidManuals[] = $pages;
47+
}
48+
}
49+
50+
foreach ($invalidManuals as $pages) {
51+
usort($pages, function ($a, $b) use ($checks): int {
52+
foreach ($checks as $check) {
53+
if ($check[0] === $a && $check[1] === $b) {
54+
return -1;
55+
}
56+
if ($check[0] === $b && $check[1] === $a) {
57+
return 1;
58+
}
59+
}
60+
return 0;
61+
});
62+
63+
$sum2 += $pages[(count($pages)-1)/2];
64+
}
65+
66+
67+
68+
echo "Part 1: ", $sum1, "\nPart 2: ", $sum2, "\n";
69+
70+
echo microtime(true) - $start;
71+
echo "\n";

php/2024/05/example.txt

226 Bytes
Binary file not shown.

php/2024/05/input.txt

14.9 KB
Binary file not shown.

0 commit comments

Comments
 (0)