-
Notifications
You must be signed in to change notification settings - Fork 0
/
d18_2.php
89 lines (73 loc) · 2.72 KB
/
d18_2.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
<?php
function exec_prog($ins, $prog_id, $send_to_prog_id, &$data)
{
// It should stop processing when it sees there's nothing else to receive
while (1) {
$data['runs']++;
$in = $ins[$data['cur'][$prog_id]];
$parts = explode(' ', substr($in, 4));
if (!isset($data['vals'][$prog_id][$parts[0]])) {
if ($parts[0] === 'p') {
$data['vals'][$prog_id][$parts[0]] = $prog_id;
} else {
// the intval() because of the freaking "jgz 1 3" instruction
$data['vals'][$prog_id][$parts[0]] = intval($parts[0]);
}
}
$val = 0;
if (count($parts) > 1) {
if (!is_numeric($parts[1])) {
$val = $data['vals'][$prog_id][$parts[1]];
} else {
$val = intval($parts[1]);
}
}
switch (substr($in, 0, 3)) {
case 'snd':
array_push($data['queue'][$send_to_prog_id], $data['vals'][$prog_id][$parts[0]]);
$data['sent_count'][$prog_id]++;
break;
case 'set':
$data['vals'][$prog_id][$parts[0]] = $val;
break;
case 'add':
$data['vals'][$prog_id][$parts[0]] += $val;
break;
case 'mul':
$data['vals'][$prog_id][$parts[0]] *= $val;
break;
case 'mod':
$data['vals'][$prog_id][$parts[0]] = $data['vals'][$prog_id][$parts[0]] % $val;
break;
case 'rcv':
if (count($data['queue'][$prog_id]) > 0) {
$data['vals'][$prog_id][$parts[0]] = array_shift($data['queue'][$prog_id]);
} else {
// Nothing to receive. Return current position and wait.
return;
}
break;
case 'jgz':
if ($data['vals'][$prog_id][$parts[0]] > 0) {
$data['cur'][$prog_id] += $val;
continue 2;
}
break;
}
$data['cur'][$prog_id]++;
}
}
// Instructions
$ins = file('input_d18.txt', FILE_IGNORE_NEW_LINES);
$data = [
'vals' => [0 => [], 1 => []],
'queue' => [0 => [], 1 => []],
'sent_count' => [0 => 0, 1 => 0],
'cur' => [0 => 0, 1 => 0],
'runs' => 0
];
while ($data['cur'][0] === 0 || count($data['queue'][0]) > 0 || count($data['queue'][1]) > 0) {
if ($data['cur'][0] === 0 || count($data['queue'][0]) > 0) exec_prog($ins, 0, 1, $data);
if ($data['cur'][1] === 0 || count($data['queue'][1]) > 0) exec_prog($ins, 1, 0, $data);
}
var_dump($data['runs'], $data['sent_count'][1]);