Skip to content

Instantly share code, notes, and snippets.

@Hc747
Created September 7, 2018 04:39
Show Gist options
  • Save Hc747/52a7488f18093c172a5ece0ebb364de1 to your computer and use it in GitHub Desktop.
Save Hc747/52a7488f18093c172a5ece0ebb364de1 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
import java.util.Stack;
public class Mindmelt {
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
Interpreter interpreter = new Interpreter(scanner.nextLine().toCharArray());
String command;
while (scanner.hasNextLine() && (command = scanner.nextLine()) != null) {
if (command.trim().isEmpty())
break;
interpreter.interpret(command.toCharArray());
}
}
}
static class Interpreter {
Interpreter(char[] i) {
this.inputBuffer = i;
}
char[] inputBuffer;
byte[] memory = new byte[30_000];
int pointer, read;
Stack<Integer> jumps = new Stack<>();
void interpret(char[] commands) {
for (int index = 0; index < commands.length; index++) {
char command = commands[index];
switch (command) {
case '+':
memory[pointer]++;
break;
case '-':
memory[pointer]--;
break;
case '>':
pointer++;
break;
case '<':
pointer--;
break;
case '[':
if (memory[pointer] != 0)
jumps.push(index);
break;
case ']':
int jmp = jumps.pop();
if (memory[pointer] != 0)
index = jmp - 1;
break;
case '.':
System.out.print(Character.toChars(memory[pointer]));
break;
case ',':
memory[pointer] = (byte) ((char) inputBuffer[read++]);
break;
default:
break;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment