-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathturingmachine.py
More file actions
78 lines (67 loc) · 2.48 KB
/
turingmachine.py
File metadata and controls
78 lines (67 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from random import randint, random
from time import perf_counter
from math import pow
import numpy as np
MIN_STATES = 5
MAX_STATES = 5
DIR_LIST = ['U','D','L','R']
class TuringMachine:
totalReadTime = 0.0
totalUpdateTime = 0.0
overallTime = 0.0
def __init__(self, tape : np.ndarray, gridSize, startPos, stateRange = (MIN_STATES, MAX_STATES), program : str = None):
self.tape = tape
self.trf = {}
self.head = list(startPos)
self.gridSize = gridSize
self.state = 0
if program is not None:
for line in program.splitlines():
s1, r, s2, w, dir = line.split(',')
self.trf[int(s1),r.lower() == 'true'] = (int(s2), w.lower() == 'true', dir)
else:
numStates = randint(stateRange[0], stateRange[1])
for s1 in range(numStates):
for r in range(0,2):
self.trf[s1,bool(r)] = (randint(0,numStates-1), bool(randint(0,1)), DIR_LIST[randint(0,3)])
def step(self):
updatePos1 = None
updatePos2 = None
changed = False
state, tape = self.state, self.tape
head_x, head_y = self.head
r = tape[head_x][head_y] # False = disabled, True = enabled
action = self.trf.get((state, r))
if action:
s2, w, dir = action
changed = r != w
tape[head_x, head_y] = w
self.moveHead(dir)
updatePos2 = tuple(self.head)
self.state = s2
updatePos1 = (head_x, head_y) if changed else None
return updatePos1, updatePos2
def moveHead(self, dir : str):
if dir == 'L':
self.head[0] -= 1
if self.head[0] < 0:
self.head[0] += self.gridSize[0]
elif dir == 'R':
self.head[0] += 1
if self.head[0] >= self.gridSize[0]:
self.head[0] -= self.gridSize[0]
elif dir == 'U':
self.head[1] -= 1
if self.head[1] < 0:
self.head[1] += self.gridSize[1]
elif dir == 'D':
self.head[1] += 1
if self.head[1] >= self.gridSize[1]:
self.head[1] -= self.gridSize[1]
else:
raise 'You done entered a wrong direction.'
def __str__(self):
output = ''
for (s1,r),(s2,w,dir) in self.trf.items():
output += str(s1) + ',' + str(r) + ',' + str(s2) + ',' + str(w) + ',' + str(dir) + '\n'
return output[:-1]