Skip to content

Instantly share code, notes, and snippets.

@JarnaChao09
Last active May 20, 2023 22:14
Show Gist options
  • Save JarnaChao09/68cc480d747d578c4f95a6fd41277e00 to your computer and use it in GitHub Desktop.
Save JarnaChao09/68cc480d747d578c4f95a6fd41277e00 to your computer and use it in GitHub Desktop.
func asciiToString(code: Integer): String {
val digits = "0123456789";
val lowerAlphabet = "abcdefghijklmnopqrstuvwxyz";
val upperAlphabet = lowerAlphabet.uppercase();
match {
code == 32: return " ";
code == 33: return "!";
code - 48 >= 0 && code - 48 < 10: return digits[code - 48];
code - 65 >= 0 && code - 65 < 26: return upperAlphabet[code - 65];
code - 97 >= 0 && code - 97 < 26: return lowerAlphabet[code - 97];
else: return "";
}
}
struct Interpreter {
val instructions: List<String>;
val buffer: List<Integer>;
val input: String;
var output: String;
var ip: Integer; // instruction pointer
var dp: Integer; // data pointer
var inp: Integer; // input pointer
var op: Integer; // output pointer;
func interpret(this): String throws Exception {
while (this.ip < this.instructions.size) {
val instruction = this.instructions[this.ip];
this.ip = this.ip + 1;
match (instruction) {
"<": this.dp = this.dp - 1;
">": this.dp = this.dp + 1;
"+": this.buffer[this.dp] = this.buffer[this.dp] + 1;
"-": this.buffer[this.dp] = this.buffer[this.dp] - 1;
",": {
this.buffer[this.dp] = this.input[this.inp].to!(Integer);
this.inp = this.inp + 1;
}
".": this.output = this.output + this.buffer[this.dp].|asciiToString();
"[": this.handleLoopStart!();
"]": this.handleLoopEnd!();
_: return "unreachable";
}
}
return this.output;
}
func handleLoopStart(this) throws Exception {
if (this.buffer[this.dp] != 0) {
return;
}
var depth = 1;
while (this.ip < this.instructions.size) {
val instruction = this.instructions[this.ip];
this.ip = this.ip + 1;
match (instruction) {
"[": depth = depth + 1;
"]": {
depth = depth - 1;
if (depth == 0) {
return;
}
}
_: {}
}
}
throw Exception("Could not find ]");
}
func handleLoopEnd(this) throws Exception {
var depth = 0;
while (this.ip > 0) {
this.ip = this.ip - 1;
val instruction = this.instructions[this.ip];
match (instruction) {
"]": depth = depth + 1;
"[": {
depth = depth - 1;
if (depth == 0) {
return;
}
}
_: {}
}
}
throw Exception("Could not find [");
}
}
func brainf__k(prog: String, input: String, bufferSize: Integer): String {
try {
return Interpreter({
instructions: prog.chars(),
buffer: [0] * bufferSize,
input: input,
output: "",
ip: 0,
dp: 0,
inp: 0,
op: 0,
}).interpret!();
} catch (val e: Exception) {
return "Failed with " + e.message;
}
}
val prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.";
val output = brainf__k(prog, "", 10);
print(output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment