a quick and dirty turing machine simulator, written in C89.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

93 lines
2.1 KiB

#include <stdio.h>
#define TAPE_SIZE 80
#define RULES_SIZE 256
typedef struct {
char state; /* current state */
char symbol; /* current symbol */
int head; /* index of head */
char tape[TAPE_SIZE]; /* tape of characters */
int nrules; /* number of rules */
/* state, symbol, new state, new symbol, direction (even right, odd left ) */
char rules[RULES_SIZE][5];
} Machine;
Machine m;
int nsteps;
int main(int argc, char *argv[]){
int i,n=0;
FILE *f;
if(!(f = fopen(argv[1], "r"))){
fprintf(stderr, "failed to load file\n");
return 1;
}
printf("%s\n\n", argv[1]);
/* read machine description */
printf("initial state: ");
fscanf(f,"%c",&m.state);
printf("%c\n",m.state);
printf("initial tape: ");
fscanf(f,"%s",m.tape);
printf("%s\n",m.tape);
printf("initial position of head: ");
fscanf(f,"%d",&m.head);
m.head = (m.head+TAPE_SIZE)%TAPE_SIZE;
printf("%d\n",m.head);
printf("number of rules: ");
fscanf(f,"%d",&m.nrules);
printf("%d\n",m.nrules);
for(i=0; i<m.nrules; i++){
printf("rule number %d: ",i);
fscanf(f,"%s",m.rules[i]);
printf("%s\n",m.rules[i]);
}
printf("max number of simulation steps: ");
fscanf(f,"%d",&nsteps);
printf("%d\n\n",nsteps);
/* simulate */
int irules; /* rules index */
do{
printf("step %d\n",n);
/* print head and state */
for(i=0; i<m.head; i++)
printf(" ");
printf("%c\n",m.state);
/* print tape: */
printf("%s\n",m.tape);
/* get symbol at head position */
m.symbol = m.tape[ m.head ];
/* search for corresponding rule */
irules = -1;
for(i=0; i<m.nrules && irules<0; i++)
if(m.rules[i][0] == m.state && m.rules[i][1] == m.symbol)
irules = i;
if( irules == -1) /* halt if not found */
printf("halted\n");
else{ /* update machine otherwise */
m.state = m.rules[irules][2]; /* new state */
m.tape[ m.head ] = m.rules[irules][3]; /* new symbol */
/* move head */
if( m.rules[irules][4]%2 ) /* if odd, move to left */
m.head = (m.head-1+TAPE_SIZE)%TAPE_SIZE;
else /* if even, move to right */
m.head = (m.head+1)%TAPE_SIZE;
}
printf("\n");
}while( ++n<nsteps && irules != -1);
return 0;
}