Repository navigation
Expand file tree
/
Copy pathmachine.cpp
More file actions
90 lines (77 loc) · 2.03 KB
/
Copy pathmachine.cpp
File metadata and controls
90 lines (77 loc) · 2.03 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
79
80
81
82
83
84
85
86
87
88
89
90
#include "machine.h"
namespace Turing
{
Machine::Machine() {
m_headPosition = m_state = 0;
m_tapes.push_back(Tape());
}
void Machine::reset(int numTapes) {
m_headPosition = m_state = 0;
while (m_tapes.count() < numTapes)
m_tapes.push_back(Tape());
while (m_tapes.count() > numTapes)
m_tapes.pop_back();
for (int i = 0; i < m_tapes.count(); i++)
m_tapes[i].Erase();
}
void Machine::execute(QList<Command> *commands, int commandsToExecute) {
bool executed, executeAllCommands = commandsToExecute == 0;
do {
executed = false;
if (executeAllCommands || commandsToExecute > 0)
for (int i = 0; i < commands->count(); i++) {
Command command = (*commands)[i];
if (command.state == m_state) {
int valid = 0;
for (int j = 0; j < command.conditions.count(); j++)
if (m_tapes.count() >= j + 1 && command.conditions.count() >= j + 1 && m_tapes[j].CellSymbol(m_headPosition) == command.conditions[j])
valid++;
if (valid == m_tapes.count()) {
for (int j = 0; j < command.conditions.count(); j++)
m_tapes[j].SetCellSymbol(m_headPosition, command.changes[j]);
if (!executeAllCommands)
commandsToExecute--;
executed = true;
if (command.direction > 0)
m_headPosition++;
else if (command.direction < 0)
m_headPosition--;
m_state = command.destination;
}
}
}
} while (executed);
}
void Machine::addTape() {
m_tapes.push_back(Tape());
}
bool Machine::removeTapeAt(int index) {
if (index < 0 || index >= m_tapes.count())
return false;
else
{
m_tapes.removeAt(index);
return true;
}
}
QList<Tape>* Machine::tapes() {
return &m_tapes;
}
int Machine::headPosition() {
return m_headPosition;
}
bool Machine::setHeadPosition(int headPosition) {
if (headPosition >= -999999 && headPosition <= 999999) {
m_headPosition = headPosition;
return true;
}
else
return false;
}
int Machine::state() {
return m_state;
}
void Machine::setState(int state){
m_state = state;
}
}