-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpackets.php
executable file
·83 lines (67 loc) · 1.6 KB
/
packets.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/php
<?php
function compare($a, $b) {
if(is_int($a)) {
if(is_int($b)) {
return $a <=> $b;
} else {
return compare([$a], $b);
}
} else if(is_int($b)) {
return compare($a, [$b]);
}
$countA = count($a);
$countB = count($b);
for($i = 0; ; ++$i) {
if(($i >= $countA)) {
return ($countA < $countB) ? -1 : 0;
}
if($i >= $countB) {
return +1;
}
$cmp = compare($a[$i], $b[$i]);
if($cmp !== 0) return $cmp;
}
}
$p1 = [];
$packets = [];
$pairNo = 1;
while(true) {
$first = fgets(STDIN);
if($first === false) break;
$first = trim($first);
if($first === "") continue; // Allow any number of empty lines
$second = fgets(STDIN);
if($second === false) {
fprintf(STDERR, "Error: Unexpected end of input\n");
die(1);
}
$second = trim($second);
// yeah yeah, eval() is evil, yadda yadda - fight me, mate
$first = eval("return " . $first . ";");
$second = eval("return " . $second . ";");
if(compare($first, $second) === -1) {
$p1[] = $pairNo;
}
array_push($packets, $first, $second);
++$pairNo;
}
echo "Part 1: ", array_sum($p1), " (", implode(', ', $p1), ")\n";
# -- part 2
$twoPack = [[2]];
$sixPack = [[6]];
array_push($packets, $twoPack, $sixPack);
usort($packets, "compare");
$twoPos = null;
$sixPos = null;
foreach($packets as $idx => $pack) {
if(($twoPos === null) && ($pack === $twoPack)) {
$twoPos = ($idx + 1);
if($sixPos === null) continue; else break;
}
if(($sixPos === null) && ($pack === $sixPack)) {
$sixPos = ($idx + 1);
if($twoPos === null) continue; else break;
}
}
echo "Part 2: ", $twoPos * $sixPos, " (", $twoPos, ", ", $sixPos, ")\n";