turing.c (1352B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <stdbool.h> 5 6 typedef struct transfer { 7 int id; 8 char input; 9 int next; 10 char output; 11 int move; 12 bool end; 13 } transfer; 14 15 transfer transfers[128]; 16 int transferptr = 0; 17 int count = 0; 18 19 char tape[4096] = {0}; 20 char *head = tape; 21 22 int main() { 23 FILE *f = fopen("test.mac", "r"); 24 25 strcat(tape, "1110"); 26 27 char *line = malloc(128); 28 while (fgets(line, 128, f) != NULL) { 29 char *tok = strtok(line, " "); // input 30 transfers[count].id = atoi(tok); 31 32 tok = strtok(NULL, " "); 33 if (tok[0] == '*') transfers[count].input = -1; 34 else transfers[count].input = tok[0]; 35 36 tok = strtok(NULL, " "); // next 37 transfers[count].next = atoi(tok); 38 39 tok = strtok(NULL, " "); // output 40 transfers[count].output = tok[0]; 41 42 tok = strtok(NULL, " "); // offset 43 transfers[count].move = atoi(tok); 44 45 tok = strtok(NULL, " "); // end 46 transfers[count].end = atoi(tok); // must be 1 or 0 47 48 count++; 49 50 line = malloc(128); 51 } 52 53 for (;;) { 54 for (int i = 0; i < count; i++) { 55 if (transfers[i].id == transferptr) { 56 if (transfers[i].input == -1 || *head == transfers[i].input) { 57 *head = transfers[i].output; 58 head += transfers[i].move; 59 transferptr = transfers[i].next; 60 if (transfers[transferptr].end) break; 61 break; 62 } 63 } 64 } 65 } 66 printf("%s\n", tape); 67 return 0; 68 } 69