Last active
August 29, 2015 13:56
-
-
Save fayimora/8817259 to your computer and use it in GitHub Desktop.
Turing Machine/Program Simulation for ECS631 Assignment
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
import sys, argparse | |
args, res = None, None | |
def info(tape, n, config): | |
"""Do shananigans before any computation""" | |
if(args.verbose): | |
print("Config: %s" % config) | |
print("Cursor is at %d" % n) | |
print("Tape is ") | |
if(args.strings): | |
res = ''.join(map(lambda i: str(i), tape)) | |
print(res) | |
else: | |
res = tape | |
print(res) | |
print("=" * len(tape)) | |
def f(tape, n): | |
info(tape, n, "f") | |
pos = n | |
if(tape[pos] == '0' or tape[pos] == '1'): | |
pos += 2 # move to the right twice | |
f(tape, pos) | |
elif(tape[pos] == ''): | |
tape[pos] = '0' | |
pos -= 2 # move to the left twice | |
c(tape, pos) | |
def p(tape, n): | |
info(tape, n, "p") | |
pos = n | |
if(tape[pos] == 'x'): | |
tape[pos] = '' | |
pos += 1 # move to the right once | |
q(tape, pos) | |
elif(tape[pos] == 'e'): | |
pos += 1 # move to the right once | |
f(tape, pos) | |
elif(tape[pos] == ''): | |
pos -= 2 # move to the left twice | |
p(tape, pos) | |
def q(tape, n): | |
info(tape, n, "q") | |
pos = n | |
if(tape[pos] == '0' or tape[pos] == '1'): | |
pos += 2 # move to the right twice | |
q(tape, pos) | |
elif(tape[pos] == ''): | |
tape[pos] = '1' | |
pos -= 1 # move to the left once | |
p(tape, pos) | |
def c(tape, n): | |
info(tape, n, "c") | |
pos = n | |
if(tape[pos] == '1'): | |
pos += 1 # move to the right once | |
tape[pos] = 'x' | |
pos -= 3 # move to the left 3 times | |
c(tape, pos) | |
elif(tape[pos] == '0'): | |
q(tape, pos) | |
def b(tape, n): | |
info(tape, n, "b") | |
pos = n | |
if tape[pos] == 'e': | |
tape[pos] = 'e' | |
pos += 1 # move to the right once | |
tape[pos] = '0' | |
pos += 2 # move to the right twice | |
tape[pos] = '0' | |
pos -= 2 | |
c(tape, pos) | |
def main(args): | |
tape, n = ['e'], 0 | |
for i in range(0, args.tape_length): tape.append('') | |
try: | |
b(tape, n) | |
except IndexError: | |
print("Stopped for now") | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser("A simulation of a turing program computinga sequence") | |
parser.add_argument('tape_length', type=int, help='The length of the tape') | |
parser.add_argument('-s', '--strings', action='store_true', default=False, help='print strings rather than arrays') | |
parser.add_argument('-v', '--verbose', action='store_true', default=False, help='Verbose mode. Print all helpful messages') | |
args = parser.parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment