-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaoc16
More file actions
71 lines (65 loc) · 2.12 KB
/
aoc16
File metadata and controls
71 lines (65 loc) · 2.12 KB
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
hex = document.getElementsByTagName("pre")[0].innerText.split("\n").filter(function(n){return n;})[0];
arr = hex.split("").map(function(i){str='000' + parseInt(i, 16).toString(2);return str.substring(str.length-4)}).join("");
var currentPosition = 0;
var versionSum = 0;
function read(start, len) {
str = '';
for (i=start;i<start+len;i++) {
str+=arr[i];
}
return parseInt(str, 2);
}
function readPacket() {
var packet = {}
packet.version = read(currentPosition, 3);
versionSum+=packet.version;
packet.type = read(currentPosition + 3, 3);
if (packet.type == 4) {
currentPosition += 6;
packet.val = 0;
//literal
while (true) {
packet.val = packet.val * 16 + read(currentPosition+1, 4);
currentPosition += 5;
if (arr[currentPosition-5] == '0') {
break;
}
}
} else {
//operator
if (arr[currentPosition + 6] == '0') {
currentPosition += 7;
var len = read(currentPosition, 15);
currentPosition += 15;
var endOfPacket = currentPosition + len;
packet.subpackets = [];
while (currentPosition < endOfPacket) {
packet.subpackets.push(readPacket());
}
} else {
currentPosition += 7;
var subPacketNumber = read(currentPosition, 11);
currentPosition += 11;
packet.subpackets = [];
while (packet.subpackets.length < subPacketNumber) {
packet.subpackets.push(readPacket());
}
}
}
return packet;
}
x=readPacket();
function calculate(packet) {
console.log(packet);
switch (packet.type) {
case 0: return packet.subpackets.map(calculate).reduce(function(a,b){return a+b});
case 1: return packet.subpackets.map(calculate).reduce(function(a,b){return a*b});
case 2: return packet.subpackets.map(calculate).reduce(function(a,b){return Math.min(a,b)});
case 3: return packet.subpackets.map(calculate).reduce(function(a,b){return Math.max(a,b)});
case 4: return packet.val;
case 5: return (calculate(packet.subpackets[0]) > calculate(packet.subpackets[1])) ? 1 : 0;
case 6: return (calculate(packet.subpackets[0]) < calculate(packet.subpackets[1])) ? 1 : 0;
case 7: return (calculate(packet.subpackets[0]) ==calculate(packet.subpackets[1])) ? 1 : 0;
}
}
result=calculate(x);