Skip to content

Instantly share code, notes, and snippets.

@fogleman
Created May 15, 2013 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fogleman/5581116 to your computer and use it in GitHub Desktop.
Save fogleman/5581116 to your computer and use it in GitHub Desktop.
2-D Turing Machine
#define NORTH 0
#define SOUTH 1
#define EAST 2
#define WEST 3
typedef struct {
int width; // width of the 2-D tape
int height; // height of the 2-D tape
int states; // number of states
int symbols; // number of symbols
int position; // current head position
int state; // current state
int *table; // transition table
int *tape; // tape memory
} Model;
void update(Model *model) {
// read symbol written on tape at head position
int symbol = model->tape[model->position];
// get base index in transition table based on symbol and current state
int index = (symbol * model->states + model->state) * 3;
// write new symbol to tape
model->tape[model->position] = model->table[index];
// set new state
model->state = model->table[index + 1];
// update head position
int x = model->position % model->width;
int y = model->position / model->width;
switch (model->table[index + 2]) {
case NORTH:
y--;
y = y < 0 ? model->height - 1 : y;
break;
case SOUTH:
y++;
y = y < model->height ? y : 0;
break;
case EAST:
x++;
x = x < model->width ? x : 0;
break;
case WEST:
x--;
x = x < 0 ? model->width - 1 : x;
break;
}
model->position = y * model->width + x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment