@@ -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
61108module . exports = {
0 commit comments