-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-19.php
61 lines (52 loc) · 2.48 KB
/
day-19.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
<?php
$input = trim(file_get_contents('input/' . substr(basename(__FILE__), 0, -4)));
$start = microtime(true);
$input = explode("\n", $input);
$ipValue = (int) explode(' ', array_shift($input))[1];
$program = [];
foreach ($input as $line) {
$part = explode(' ', $line);
$program[] = [$part[0], (int) $part[1], (int) $part[2], (int) $part[3]];
}
$steps = count($program);
$functions = [
'addr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] + $reg[$b]; },
'addi' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] + $b; },
'mulr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] * $reg[$b]; },
'muli' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] * $b; },
'banr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] & $reg[$b]; },
'bani' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] & $b; },
'borr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] | $reg[$b]; },
'bori' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] | $b; },
'setr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a]; },
'seti' => function($a, $b, $c, array &$reg) { $reg[$c] = $a; },
'gtir' => function($a, $b, $c, array &$reg) { $reg[$c] = $a > $reg[$b] ? 1 : 0; },
'gtri' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] > $b ? 1 : 0; },
'gtrr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] > $reg[$b] ? 1 : 0; },
'eqir' => function($a, $b, $c, array &$reg) { $reg[$c] = $a === $reg[$b] ? 1 : 0; },
'eqri' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] === $b ? 1 : 0; },
'eqrr' => function($a, $b, $c, array &$reg) { $reg[$c] = $reg[$a] === $reg[$b] ? 1 : 0; },
];
foreach (range(0, 1) as $part) {
$pointer = -1;
$registers = [$part, 0, 0, 0, 0, 0];
$counter = 0;
while (++$pointer < $steps) {
$instr = $program[$pointer];
$registers[$ipValue] = $pointer;
$functions[$instr[0]]($instr[1], $instr[2], $instr[3], $registers);
$pointer = $registers[$ipValue];
if ($counter++ > 50) {
$sqrt = (int) sqrt($registers[5]);
$result = 0;
for ($i = 1; $i <= $sqrt; $i++) {
if ($registers[5] % $i === 0) {
$result += $i + $registers[5] / $i;
}
}
echo 'Answer ' . ($part + 1) . ': ' . $result . PHP_EOL;
break;
}
}
}
echo 'Execution time: ' . (microtime(true) - $start) . PHP_EOL;