Skip to content

Commit 0a2eff9

Browse files
committed
Part 2 doesn't work!
Ahh seems like it should but I'm getting undefined!
1 parent 81facdd commit 0a2eff9

File tree

3 files changed

+52
-3
lines changed

3 files changed

+52
-3
lines changed

2019/23/network.js

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class Network {
3939
});
4040
}
4141

42-
run(break_on_address = 255) {
42+
partOne(break_on_address = 255) {
4343
while (true) {
4444
for (let nic of this.nics) {
4545
let outputs = nic.run();
@@ -56,6 +56,53 @@ class Network {
5656
}
5757
}
5858
}
59+
60+
partTwo(nat_address = 255) {
61+
let nat_packet;
62+
let last_nat_sent = [];
63+
64+
const IDLE_REST = 200;
65+
66+
// Some arbitrary number of loops to test if "idle"
67+
let idle = IDLE_REST;
68+
while (true) {
69+
idle--;
70+
for (let nic of this.nics) {
71+
let outputs = nic.run();
72+
if (outputs.length === 3) {
73+
idle = IDLE_REST;
74+
let address = outputs.shift();
75+
let x = outputs.shift();
76+
let y = outputs.shift();
77+
78+
if (address === nat_address) {
79+
nat_packet = [x, y];
80+
} else {
81+
this.packet_queue[address].push([x, y]);
82+
}
83+
}
84+
}
85+
86+
if (idle < 0 && this.packetQueueSize() === 0) {
87+
// Once the network is idle, the NAT sends only the last packet
88+
// it received to address 0.
89+
this.packet_queue[0].push(nat_packet);
90+
91+
// What is the first Y value delivered by the NAT to the computer at address 0 twice in a row?
92+
if (last_nat_sent[1] === nat_packet[1]) {
93+
return { x: nat_packet[0], y: nat_packet[1] };
94+
}
95+
96+
// @todo Reset NAT packet here?, e.g. `nat_packet = undefined`?
97+
last_nat_sent = nat_packet;
98+
idle = IDLE_REST;
99+
}
100+
}
101+
}
102+
103+
packetQueueSize() {
104+
return this.packet_queue.reduce((sum, queue) => sum + queue.length, 0);
105+
}
59106
}
60107

61108
module.exports = {

2019/23/part-one.js

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,4 @@ const { input } = require('./input');
22
const { Network } = require('./network');
33

44
let network = new Network(input);
5-
let net_packet = network.run();
6-
console.log(net_packet);
5+
console.log(network.partOne());

2019/23/part-two.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
11
const { input } = require('./input');
2+
const { Network } = require('./network');
23

4+
let network = new Network(input);
5+
console.log(network.partTwo());

0 commit comments

Comments
 (0)