summaryrefslogtreecommitdiff
path: root/comp/work/46/turing.c
blob: cc414510d52949af3b910d9ec092d2aab5db6db7 (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct transfer {
	int id;
	char input;
	int next;
	char output;
	int move;
	bool end;
} transfer;

transfer transfers[128];
int transferptr = 0;
int count = 0;

char tape[4096] = {0};
char *head = tape;

int main() {
	FILE *f = fopen("test.mac", "r");

	strcat(tape, "1110");

	char *line = malloc(128);
	while (fgets(line, 128, f) != NULL) {
		char *tok = strtok(line, " "); // input
		transfers[count].id = atoi(tok);
		
		tok = strtok(NULL, " ");
		if (tok[0] == '*') transfers[count].input = -1;
		else transfers[count].input = tok[0];

		tok = strtok(NULL, " ");  // next
		transfers[count].next = atoi(tok);

		tok = strtok(NULL, " "); // output
		transfers[count].output = tok[0];

		tok = strtok(NULL, " "); // offset
		transfers[count].move = atoi(tok);

		tok = strtok(NULL, " "); // end
		transfers[count].end = atoi(tok); // must be 1 or 0

		count++;

		line = malloc(128);
	}

	for (;;) {
		for (int i = 0; i < count; i++) {
			if (transfers[i].id == transferptr) {
				if (transfers[i].input == -1 || *head == transfers[i].input) {
					*head = transfers[i].output;
					head += transfers[i].move;
					transferptr = transfers[i].next;
					if (transfers[transferptr].end) break;
					break;
				}
			}
		}
	}
	printf("%s\n", tape);
	return 0;
}