|
| 1 | +/* |
| 2 | +declare let input: string; |
| 3 | +declare let output: any; |
| 4 | +copy(text: string): text |
| 5 | +print(text: string): undefined |
| 6 | +*/ |
| 7 | + |
| 8 | +let inv = input.split`,`; |
| 9 | +inv[1] = 12; |
| 10 | +inv[2] = 2; |
| 11 | + |
| 12 | +class V { |
| 13 | + constructor() { |
| 14 | + this.memory = inv.map(v => +v); |
| 15 | + this.go = true; |
| 16 | + this.index = 0; |
| 17 | + } |
| 18 | + stop() { |
| 19 | + this.go = false; |
| 20 | + } |
| 21 | + get i() { |
| 22 | + return this.index; |
| 23 | + } |
| 24 | + set i(nv) { |
| 25 | + let prevV = this.index; |
| 26 | + this.index = nv; |
| 27 | + } |
| 28 | + get n() { |
| 29 | + // *(index++) |
| 30 | + return this.getAt(this.i++); |
| 31 | + } |
| 32 | + get p() { |
| 33 | + // *(*(index++)) |
| 34 | + return this.getAt(this.n); |
| 35 | + } |
| 36 | + get m() { |
| 37 | + return this.memory; |
| 38 | + } |
| 39 | + boundsCheck(index) { |
| 40 | + if (index > this.m.length - 1 || index < 0) { |
| 41 | + throw new Error("out of bounds (" + index + " / " + this.m.length + ")"); |
| 42 | + } |
| 43 | + } |
| 44 | + getAt(index) { |
| 45 | + this.boundsCheck(index); |
| 46 | + return this.memory[index]; |
| 47 | + } |
| 48 | + setAt(index, value) { |
| 49 | + this.boundsCheck(index); |
| 50 | + let prevV = this.memory[index]; |
| 51 | + this.memory[index] = value; |
| 52 | + return prevV; |
| 53 | + } |
| 54 | +} |
| 55 | +let v = new Proxy(new V(), { |
| 56 | + get: (obj, prop) => |
| 57 | + (+prop).toString() === prop ? obj.getAt(+prop) : obj[prop], |
| 58 | + set: (obj, prop, value) => |
| 59 | + (+prop).toString() === prop |
| 60 | + ? obj.setAt(+prop, value) |
| 61 | + : ((obj[prop] = value), true), |
| 62 | +}); |
| 63 | + |
| 64 | +let intcodes = { |
| 65 | + "1": () => { |
| 66 | + let [a, b, ri] = [v.p, v.p, v.n]; |
| 67 | + v[ri] = a + b; |
| 68 | + }, |
| 69 | + "2": () => { |
| 70 | + let [a, b, ri] = [v.p, v.p, v.n]; |
| 71 | + v[ri] = a * b; |
| 72 | + }, |
| 73 | + "99": () => { |
| 74 | + return v.stop(); |
| 75 | + }, |
| 76 | + "404": () => { |
| 77 | + console.log("uh oh! invalid instruction", v[v.i - 1]); |
| 78 | + return v.stop(); |
| 79 | + }, |
| 80 | +}; |
| 81 | + |
| 82 | +while (v.go) { |
| 83 | + let opcode = v.n; |
| 84 | + console.log("== opcode ", opcode); |
| 85 | + (intcodes["" + opcode] || intcodes["404"])(); |
| 86 | +} |
| 87 | + |
| 88 | +console.log(v.m.join(",")); |
| 89 | + |
| 90 | +output = v[0]; |
0 commit comments