-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.php
97 lines (74 loc) · 2.26 KB
/
code.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
require_once __DIR__ . '/../../lib/php/utils.php';
$input = readInput(__DIR__);
// Task code
function part01(array $input): int
{
$gamma = '';
$epsilon = '';
for ($pos = 0, $byteLength = strlen($input[0]); $pos < $byteLength; $pos++) {
$mostCommonIndex = commonBit($input, $pos);
$leastCommonIndex = $mostCommonIndex === 0 ? 1 : 0;
$gamma .= $mostCommonIndex;
$epsilon .= $leastCommonIndex;
}
return bindec($gamma) * bindec($epsilon);
}
function part02(array $input): int
{
$oxygen = filterBytes($input, true);
$carbon = filterBytes($input, false);
return bindec($oxygen) * bindec($carbon);
}
function commonBit(array $bytes, int $position): int
{
$occurrences = [0, 0];
foreach ($bytes as $byte) {
$bit = (int) $byte[$position];
$occurrences[$bit]++;
}
if ($occurrences[0] === $occurrences[1]) {
return -1;
}
return array_search(max($occurrences), $occurrences, true);
}
function filterBytes(array $input, bool $mostCommon): string
{
$bytes = $input;
for ($pos = 0, $byteLength = strlen($bytes[0]); $pos < $byteLength; $pos++) {
if (count($bytes) === 1) {
break;
}
$mostCommonIndex = commonBit($bytes, $pos);
$bytes = array_filter(
$bytes,
static function($byte) use ($mostCommonIndex, $mostCommon, $pos){
if ($mostCommonIndex === -1) {
if ($mostCommon) {
return $byte[$pos] === '1';
}
return $byte[$pos] === '0';
}
if (!$mostCommon) {
return $byte[$pos] === ($mostCommonIndex === 0 ? '1' : '0');
}
return $byte[$pos] === (string) $mostCommonIndex;
}
);
}
return current($bytes);
}
// Execute
calcExecutionTime();
$result01 = part01($input);
$result02 = part02($input);
$executionTime = calcExecutionTime();
writeln('Solution Part 1: ' . $result01);
writeln('Solution Part 2: ' . $result02);
writeln('Execution time: ' . $executionTime);
saveBenchmarkTime($executionTime, __DIR__);
// Task test
testResults(
[845186, 4636702], // Expected
[$result01, $result02], // Result
);