Last active
December 14, 2021 18:27
-
-
Save Seggan/31a0173d1a9891926276f142777f176a to your computer and use it in GitHub Desktop.
A Minimalistic Turing Machine
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
""" | |
A minimalistic Turing machine I wrote for an assignment. | |
Has 4 commands: > (unconditional branch), + (add), x (halt), and ? (branch if zero). > adds to the current | |
tape location by x, where x is the number right after the command. + adds the number in absolute | |
position a to the number in absolute position b, one-indexed, where a and b are the two numbers | |
following the command. x stops the program and prints the contents of the tape. ? checks if the previous | |
number is zero, if it is, add x to the tape position, where x is the number following the command. | |
Sample multiplication program: > 7 c a b ? 4 > 3 x + 4 3 -1 + 14 5 > -13, where c is the result | |
(initially set to 0), and a and b are the two numbers to multiply | |
""" | |
raw = input().split() | |
tape = [] | |
for n in raw: | |
try: | |
tape.append(int(n)) | |
except ValueError: | |
tape.append(n) | |
head = 0 | |
stop = False | |
while not stop: | |
match tape[head]: | |
case '>': | |
head += tape[head + 1] | |
case 'x': | |
stop = True | |
case '+': | |
tape[tape[head + 2] - 1] += tape[tape[head + 1] - 1] | |
head += 1 | |
case '?': | |
if tape[head - 1] == 0: | |
head += tape[head + 1] | |
else: | |
head += 1 | |
case _: | |
head += 1 | |
print(tape) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment