-
Notifications
You must be signed in to change notification settings - Fork 0
/
23.php
112 lines (90 loc) · 2.51 KB
/
23.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
class Duet
{
public function __construct($part = 'A')
{
$registers = range('a', 'h');
$registers = array_flip($registers);
foreach ($registers as $idx => $register) {
$registers[$idx] = 0;
}
$this->registers = $registers;
if ($part != 'A') {
$this->registers['a'] = 1;
}
$contents = trim(file_get_contents('23-input.txt'));
$this->inst = explode("\n", $contents);
$this->freq = [];
$this->mul_invoked = 0;
$this->part = $part;
}
private static function isPrime($n)
{
for ($i = $n; --$i && $n%$i;);
return $i==1;
}
private function set($x, $y)
{
$then = is_numeric($y) ? $y : $this->registers[$y];
$this->registers[$x] = (int)($then);
}
private function sub($x, $y)
{
$then = is_numeric($y) ? $y : $this->registers[$y];
$this->registers[$x] -= (int)($then);
}
private function mul($x, $y)
{
$then = is_numeric($y) ? $y : $this->registers[$y];
$this->registers[$x] *= (int)($then);
$this->mul_invoked++;
}
public function process()
{
$i = 0;
while ($i < count($this->inst)) {
$inc = true;
$input = $this->inst[$i];
$parts = explode(' ', $input);
switch ($parts[0]) {
case 'set':
case 'sub':
case 'mul':
$this->{$parts[0]}($parts[1], $parts[2]);
break;
case 'jnz':
$if = (int) is_numeric($parts[1]) ? $parts[1] : $this->registers[$parts[1]];
$then = (int) is_numeric($parts[2]) ? $parts[2] : $this->registers[$parts[2]];
if ($if != 0) {
$i += (int)($then);
$inc = false;
}
break;
default:
var_dump('error');
var_dump($input);die();
}
if ($i < 0 || $i > count($this->inst)) {
break;
}
if ($inc) {
$i++;
}
}
}
public function processB()
{
$cnt = 0;
for ($i = 108100; $i < 125100; $i += 17) {
if (! self::isPrime($i)) {
$cnt++;
}
}
return $cnt;
}
}
$c = new Duet;
$c->process();
echo 'Part A: ' . $c->mul_invoked . PHP_EOL;
$c2 = new Duet('B');
echo 'Part B: ' . $c2->processB() . PHP_EOL;