-
Notifications
You must be signed in to change notification settings - Fork 75
/
solution.js
49 lines (43 loc) · 1.11 KB
/
solution.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
const fs = require('fs');
const instructions = [...fs.readFileSync(process.argv[2] || 'input.hand', 'utf-8')];
let cursor = 0;
const data = [0];
let pointer = 0;
const loops = {};
const stack = [];
instructions.forEach((instruction, index) => {
if (instruction === '🤜') {
stack.push(index);
} else if (instruction === '🤛') {
const loopStart = stack.pop();
loops[loopStart] = index;
loops[index] = loopStart;
}
});
const actions = {
'👉': () => {
pointer += 1;
if (pointer >= data.length) {
data.push(0);
}
},
'👈': () => pointer -= 1,
'👆': () => data[pointer] = data[pointer] === 255 ? 0 : data[pointer] + 1,
'👇': () => data[pointer] = data[pointer] === 0 ? 255 : data[pointer] - 1,
'👊': () => process.stdout.write(String.fromCharCode(data[pointer])),
'🤜': () => {
if (data[pointer] === 0) {
cursor = loops[cursor];
}
},
'🤛': () => {
if (data[pointer] !== 0) {
cursor = loops[cursor];
}
},
}
while (cursor < instructions.length) {
const instruction = instructions[cursor];
actions[instruction]();
cursor += 1;
}