-
Notifications
You must be signed in to change notification settings - Fork 0
/
day8.js
102 lines (95 loc) · 2.43 KB
/
day8.js
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
90
91
92
93
94
95
96
97
98
99
100
101
102
const { readData } = require('./readfile');
const input = readData('day8Input.txt');
const lines = input.split(/\n/);
// question 1
const runBeforeInfiniteLoop = (lines) => {
let accumulator = 0;
let executed = {};
let i = 0;
let last = false;
while (i < lines.length) {
// console.log(i, executed[i], lines[i], accumulator);
if (executed[i]) {
break;
}
if (i === lines.length-1) {
console.log('Last cmd');
last = true;
}
const curLine = lines[i];
const [op, param] = curLine.split(" ");
executed[i] = true;
if(op === "acc") {
accumulator = eval(`${accumulator}${param}`);
i++;
} else if(op === "jmp") {
i = eval(`${i}${param}`);
} else {
i++;
}
}
// console.log(accumulator);
// 1134
return last? [accumulator, true]: accumulator;
}
// runBeforeInfiniteLoop(lines);
const findBadLine = (lines) => {
let executed = {};
let i = 0;
let lastJmp = 0;
while (i < lines.length) {
// console.log(i, executed[i], lines[i], accumulator);
if (executed[i]) {
break;
}
const curLine = lines[i];
const [op, param] = curLine.split(" ");
executed[i] = true;
if(op === "acc") {
i++;
} else if(op === "jmp") {
if(param[0] === '-') {
// console.log(i, lines[i])
lastJmp = i;
}
i = eval(`${i}${param}`);
} else {
i++;
}
}
return lastJmp;
}
const badLine = findBadLine(lines);
console.log('badLine'+badLine);
runBeforeInfiniteLoop(lines.map((x, i) => {
if (i === badLine) {
console.log(x)
return x.replace('jmp', 'nop')
}
return x;
}))
let j = 0;
while (j < lines.length) {
let res;
if (lines[j].slice(0,3) === 'jmp') {
res = runBeforeInfiniteLoop(lines.map((x, i) => {
if (i === j) {
return x.replace('jmp', 'nop')
}
return x;
}))
}
if (lines[j].slice(0,3) === 'nop') {
res = runBeforeInfiniteLoop(lines.map((x, i) => {
if (i === j) {
return x.replace('nop', 'jmp')
}
return x;
}))
}
if(typeof res === 'object') {
console.log('found');
console.log(res);
}
j++;
}