Repository navigation
Expand file tree
/
Copy pathTuringMachine.c
More file actions
66 lines (60 loc) · 1.72 KB
/
Copy pathTuringMachine.c
File metadata and controls
66 lines (60 loc) · 1.72 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
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "TuringMachine.h"
#define MAP(idx) ((idx) < 0 ? (-(idx)) * 2 - 1 : (idx) * 2)
static void set(char * memory, int idx, char ch) {
memory[MAP(idx)] = ch;
};
static char get(const char * memory, int idx) {
return memory[MAP(idx)];
};
#undef MAP
static void dump(const struct TuringMachine * this) {
printf("%d: ", this->location);
int i;
for (i = 0; i < 20; i++) {
printf("%c ", get(this->memory, i));
}
printf("\n");
};
void regist(struct TuringMachine * this, int s, char sch, int t, char tch, char lr) {
free(this->rules[s][sch]);
this->rules[s][sch] = malloc(sizeof(struct tuple));
this->rules[s][sch]->state = t;
this->rules[s][sch]->ch = tch;
this->rules[s][sch]->lr = lr;
};
int execute(struct TuringMachine * this, const char * s) {
this->location = 0;
this->state = 0;
memset(this->memory, 0, MEM_SIZE);
int i;
for (i = 0; *s != '\0'; i++, s++) {
set(this->memory, i, *s);
}
while (1) {
dump(this);
char chNow = get(this->memory, this->location);
struct tuple * rule;
if ((rule = this->rules[this->state][chNow])) {
set(this->memory, this->location, rule->ch);
this->state = rule->state;
if (rule->lr == 'L') {
this->location--;
} else if (rule->lr == 'R') {
this->location++;
} else {
printf("error\n");
exit(1);
}
} else {
printf("halt\n");
break;
}
}
return this->state;
};
void create(struct TuringMachine * this) {
memset(this, 0, sizeof(struct TuringMachine));
};