summaryrefslogtreecommitdiff
path: root/turing.c
blob: 4061a391ff7b9d7d467329038ed3b79159ff8954 (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct node {
	int id;
	bool end;
} node;

typedef struct connection {
	node *parrent;
	char input;
	char output;
	int offset;
	node *result;
} connection;

node nodes[128];
int nodecount = 0;

connection connections[1024];
int connectioncount = 0;

void perror(const char *msg) {
	fprintf(stderr, "%s\n", msg);
	exit(1);
}

node *findnode(int id) {
	for (int i = 0; i < nodecount; i++)
		if (nodes[i].id == id) return &nodes[i];
	return NULL;
}

int main(int argc, char **argv) {
	if (argc <= 1) perror("no file given");

	FILE *f = fopen(argv[1], "r");
	if (f == NULL) perror("failed to open file");

	/* define nodes */
	char *line = malloc(128);
	while (fgets(line, 128, f)[0] == '#') continue; /* handles comments */

	char *tok = strtok(line, " ");
	while (tok != NULL) {
		if (tok[0] == 'e') { 
			nodes[nodecount].end = true;
			tok++;
		}
		nodes[nodecount].id = atoi(tok);
		nodecount++;
		tok = strtok(NULL, " ");
	}

	/* define connections */
	node *parrent, *result;
comment:
	while (fgets(line, 128, f) != NULL) {
		if (line[0] == '#' || line[0] == '\n') goto comment;

		char *tok = strtok(line, " ");
		if ((parrent = findnode(atoi(tok))) == NULL) perror("unknown node specified");
		connections[connectioncount].parrent = parrent;

		tok = strtok(NULL, " ");
		if (tok[0] == '#') connections[connectioncount].input = 0;
		else connections[connectioncount].input = tok[0];

		tok = strtok(NULL, " ");
		if (tok[0] == '#') connections[connectioncount].output = 0;
		else connections[connectioncount].output = tok[0];

		tok = strtok(NULL, " ");
		connections[connectioncount].offset = atoi(tok);

		tok = strtok(NULL, " ");
		if ((result = findnode(atoi(tok))) == NULL) perror("unknown node specified");
		connections[connectioncount].result = result;

		connectioncount++;
	}

	char tape[4096] = {0};
	if (argc >= 3) strcat(tape, argv[2]); /* fill the tape with user input, if they give it */

	char *head = tape;
	node *current = &nodes[0];		
	
	for (;;) {
success:
		for (int i = 0; i < connectioncount; i++) {
			if (connections[i].parrent == current && connections[i].input == *head){
				*head = connections[i].output;
				current = connections[i].result;
				head += connections[i].offset;
				goto success;
			}
		}
		printf("%s\n", tape);
		printf("%s\n", (current->end) ? "accept" : "reject"); /* did it end in a valid location */
		break;
	}
		
	return 0;
}