Skip to content

Instantly share code, notes, and snippets.

@denkspuren
Created December 2, 2016 16:05
Show Gist options
  • Save denkspuren/d07f4857f82fb8515637012b6059dace to your computer and use it in GitHub Desktop.
Save denkspuren/d07f4857f82fb8515637012b6059dace to your computer and use it in GitHub Desktop.
Implementation of Turing Machine (use JShell to run)
// https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html
enum Head { LEFT, RIGHT, NONE }
class Transition { // data container only
final String from, to;
final Character read, write;
final Head move;
Transition(String from, Character read, Character write, Head move, String to) {
this.from = from;
this.read = read;
this.write = write;
this.move = move;
this.to = to;
}
public String toString() {
return from + "(" + read + "): " + write + ", " + move + " -> " + to;
}
}
class Machine {
Collection<Transition> transitions = new ArrayList<>();
Stack<Character> left = new Stack<>();
Stack<Character> right = new Stack<>();
Character empty = '.';
String state;
Machine(String left, String right) {
for(Character c : left.toCharArray()) this.left.push(c);
String thgir = new StringBuilder(right).reverse().toString();
for(Character c : thgir.toCharArray()) this.right.push(c);
}
void move(Head move) {
switch (move) {
case RIGHT:
left.push(right.isEmpty() ? empty : right.pop());
break;
case LEFT:
right.push(left.isEmpty() ? empty : left.pop());
break;
default: break;
}
}
void add(Transition t) {
if (t != null) transitions.add(t);
}
void action() {
Character symbol = right.isEmpty() ? empty : right.pop();
Transition t = find(state,symbol);
right.push(t.write);
move(t.move);
state = t.to;
}
Transition find(String state, Character read) {
for(Transition t : transitions)
if (t.from == state && t.read == read) return t;
return null;
}
void run() {
while(!state.equals("HALT"))
action();
}
public String toString() {
Stack<Character> thgir = new Stack<>();
return left + "<+>" + right;
}
}
// example from https://de.wikipedia.org/wiki/Turingmaschine
Machine m = new Machine("","11000");
m.add(new Transition("s1",'1','0',Head.RIGHT,"s2"));
m.add(new Transition("s1",'0','0',Head.NONE,"HALT"));
m.add(new Transition("s2",'1','1',Head.RIGHT,"s2"));
m.add(new Transition("s2",'0','0',Head.RIGHT,"s3"));
m.add(new Transition("s3",'1','1',Head.RIGHT,"s3"));
m.add(new Transition("s3",'0','1',Head.LEFT,"s4"));
m.add(new Transition("s4",'1','1',Head.LEFT,"s4"));
m.add(new Transition("s4",'0','0',Head.LEFT,"s5"));
m.add(new Transition("s5",'1','1',Head.LEFT,"s5"));
m.add(new Transition("s5",'0','1',Head.RIGHT,"s1"));
m.state = "s1";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment