1
1
'use strict' ;
2
2
const _ = require ( 'lodash' ) ;
3
3
const rInstr = / ( \w + ) ( [ a - d ] | - ? \d + ) (?: ( [ a - d ] | - ? \d + ) ) ? / ;
4
- const jnzCache = { } ;
4
+ const output = [ ] ;
5
5
6
6
module . exports = function ( part , data ) {
7
7
const instrs = _ . map ( data . split ( '\n' ) , ( line ) => rInstr . exec ( line ) ) ;
8
8
let ip = 0 ;
9
9
let regs = {
10
- a : part == 1 ? 7 : 12 ,
10
+ a : 0 ,
11
11
b : 0 ,
12
12
c : 0 ,
13
13
d : 0
@@ -16,7 +16,6 @@ module.exports = function(part, data) {
16
16
while ( ip < instrs . length ) {
17
17
ip = exec ( regs , instrs , ip ) ;
18
18
}
19
- console . log ( ip + ':' , regs . a , regs . b , regs . c , regs . d ) ;
20
19
} ;
21
20
22
21
function exec ( regs , instrs , ip ) {
@@ -34,30 +33,16 @@ function exec(regs, instrs, ip) {
34
33
regs [ matches [ 2 ] ] -- ;
35
34
break ;
36
35
case 'jnz' :
37
- // try to find multiply
38
- if ( / [ a - d ] / . test ( matches [ 2 ] ) ) {
39
- if ( jnzCache [ ip ] ) {
40
- const k = matches [ 2 ] ;
41
- const step = jnzCache [ ip ] [ k ] / ( jnzCache [ ip ] [ k ] - regs [ k ] ) ;
42
- _ . each ( regs , ( val , key ) => {
43
- regs [ key ] = jnzCache [ ip ] [ key ] + ( regs [ key ] - jnzCache [ ip ] [ key ] ) * step ;
44
- } ) ;
45
- delete jnzCache [ ip ] ;
46
- } else {
47
- jnzCache [ ip ] = _ . clone ( regs ) ;
48
- }
49
- }
50
-
51
36
if ( getVal ( regs , matches [ 2 ] ) ) return ip + getVal ( regs , matches [ 3 ] ) ;
52
37
break ;
53
- case 'tgl ' :
54
- const target = instrs [ ip + getVal ( regs , matches [ 2 ] ) ] ;
55
- if ( ! target ) break ;
56
-
57
- if ( typeof target [ 3 ] == 'undefined' ) {
58
- target [ 1 ] = target [ 1 ] == 'inc' ? 'dec' : 'inc' ;
38
+ case 'out ' :
39
+ const val = getVal ( regs , matches [ 2 ] ) ;
40
+ const ch = String . fromCharCode ( val ) ;
41
+ if ( ch == '\n' ) {
42
+ console . log ( output . join ( '' ) ) ;
43
+ output . length = 0 ;
59
44
} else {
60
- target [ 1 ] = target [ 1 ] == 'jnz' ? 'cpy' : 'jnz' ;
45
+ output . push ( ch ) ;
61
46
}
62
47
break ;
63
48
default :
0 commit comments