Skip to content

Instantly share code, notes, and snippets.

@ahmedengu
Last active January 30, 2016 18:24
Show Gist options
  • Save ahmedengu/3e31ccec6320fa4c1d41 to your computer and use it in GitHub Desktop.
Save ahmedengu/3e31ccec6320fa4c1d41 to your computer and use it in GitHub Desktop.
Smallest Turing Machine code :D
public class Main {
public static void main(String[] args) {
String[][] transitions = {{"qs", "1", "qs", "1", "r"},{"qs", "_", "q0", "_", "l"},{"qs", "0", "qa", "0", "r"}};
String tape = "111111100000000011", startState = "qs";
for (int headPosition = 0; !(startState.equals(("qa"))) && !(startState.equals("qr")); ) {
String[] tmpTransition = null;
for (int i = 0; i < transitions.length; i++)
if (transitions[i][1].contains("" + tape.charAt(headPosition)))
if (transitions[i][0].contains(startState))
tmpTransition = transitions[i];
if (tmpTransition != null) {
startState = tmpTransition[2];
tape = tape.substring(0, headPosition) + tmpTransition[3] + tape.substring(headPosition + 1);
} else break;
headPosition += (tmpTransition[4].contains("r")) ? 1 : -1;
if (headPosition < 0) headPosition = 0;
while (tape.length() <= headPosition) tape += "-";
}
System.out.println("final tape: " + tape +"\n"+(startState.equals("qa") ? "accept" : "reject"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment