-
Notifications
You must be signed in to change notification settings - Fork 1
/
solution.js
83 lines (75 loc) · 1.8 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
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
const solve = (commands) => {
const cpu = {
V00: 0,
V01: 0,
V02: 0,
V03: 0,
V04: 0,
V05: 0,
V06: 0,
V07: 0,
};
const checkOverflow = (result) => {
result > 255 ? (result = result - 256) : result;
result < 0 ? (result = 256 + result) : result;
return result;
};
const compile = (command, line) => {
let from, target, result;
switch (command) {
case 'MOV':
[from, target] = line.slice(4).split(',');
cpu[from]
? (cpu[target] = cpu[from])
: (cpu[target] = Number(from));
break;
case 'ADD':
[target, from] = line.slice(4).split(',');
result = checkOverflow(cpu[from] + cpu[target]);
cpu[target] = cpu[from] + cpu[target];
break;
case 'DEC':
target = line.split(' ')[1];
result = checkOverflow(cpu[target] - 1);
cpu[target] = result;
break;
case 'INC':
target = line.split(' ')[1];
result = checkOverflow(cpu[target] + 1);
cpu[target] = result;
break;
case 'JMP':
break;
}
};
for (let i = 0; i < commands.length; i++) {
const current = commands[i];
const order = current.slice(0, 3);
compile(order, current);
}
return Object.values(cpu);
};
/*
solve([
'MOV 5,V00', // V00 is 5
'MOV 10,V01', // V01 is 10
'DEC V00', // V00 is now 4
'ADD V00,V01', // V00 = V00 + V01 = 14
]);
*/
/*
solve([
'MOV 255,V00', // V00 is 255
'INC V00', // V00 is 256, overflows to 0
'DEC V01', // V01 is -1, overflows to 255
'DEC V01', // V01 is 254
]);
*/
solve([
'MOV 10,V00', // V00 is 10
'DEC V00', // decrement V00 by 1 <---┐
'INC V01', // increment V01 by 1 |
'JMP 1', // loop until V00 is 0 ----┘
'INC V06', // increment V06 by 1
]);
module.exports = { solve };