-
-
Save Oderjunkie/eff75ba4de9942d3db76ab73cc9932f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function execute(prog, input) { | |
class Tower { | |
#arr | |
#fill | |
#writeonly | |
constructor(arr, fill, writeonly = false) { | |
this.#arr = arr; | |
this.#fill = fill; | |
this.#writeonly = writeonly; | |
} | |
push(val) { | |
if (!this.#writeonly && (this.#arr.length > 0 ? val > this.#arr.at(-1) : val > this.#fill)) | |
throw new Error('ERROR: TOWERS OF HANOI RULE BORKEN'); | |
this.#arr.push(val); | |
} | |
pop() { | |
if (this.#arr.length > 0) return this.#arr.pop(); | |
return this.#fill; | |
} | |
get arr() { | |
return this.#arr; | |
} | |
} | |
let istack = new Tower(input.split('').map((_,i,a)=>a[a.length-i-1].charCodeAt(0)), 0); | |
let ostack = new Tower([], 0, true); | |
let stack1 = new Tower([], 255); | |
let stack2 = new Tower([], 255); | |
let stack3 = new Tower([], 255); | |
for (const char of prog) | |
switch (char) { | |
case '-': { | |
let a = stack2.pop(); | |
let b = stack2.pop(); | |
stack2.push(b); | |
stack2.push(b - a); | |
break; | |
} | |
case '>': { | |
let a = stack2.pop(); | |
stack2.push(a); | |
stack2.push(a); | |
break; | |
} | |
case '<': { | |
let a1 = stack2.pop(); | |
let a2 = stack2.pop(); | |
if (a1 != a2) | |
throw new Error('ERROR: IRREVERSIBLE OPERATION'); | |
stack2.push(a1); | |
break; | |
} | |
case '(': { | |
let x = stack1.pop(); | |
stack2.push(x); | |
break; | |
} | |
case ')': { | |
let x = stack2.pop(); | |
stack1.push(x); | |
break; | |
} | |
case '[': { | |
let x = stack3.pop(); | |
stack2.push(x); | |
break; | |
} | |
case ']': { | |
let x = stack2.pop(); | |
stack3.push(x); | |
break; | |
} | |
case '{': { | |
let x = istack.pop(); | |
stack2.push(x); | |
break; | |
} | |
case '}': { | |
let x = stack2.pop(); | |
ostack.push(x); | |
break; | |
} | |
} | |
return ostack.arr.map((_,i,a) => String.fromCharCode(a[a.length - i - 1])).join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment