Snippets

Matthew Jadud ABA Machine

Created by Matthew Jadud
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>

/* Define the possible states as integers. */
#define STATE_START       0
#define STATE_READING_A   1
#define STATE_READING_B   2
#define STATE_ACCEPT      3
#define STATE_REJECT      4

bool isAtEnd (int v) {
  return (v == EOF) || (v == '\n') || (v == '\r');
}

int main (int argc, char *argv[]) {

  FILE *input_string;
  input_string = fopen(argv[1], "r");

  int next;
  bool RUNNING = true;
  
  int state = STATE_START;
  
  while (RUNNING) {
    next = fgetc(input_string);
    sleep(1);
    
    switch (state) {
      
      case STATE_START:
        printf("STATE_START\n");
        printf ("NEXT: %c\n", next);
        
        if (next == 'a') {
          state = STATE_READING_A;        
        } else if (next == 'b') {
          state = STATE_READING_B;
        }
       break;

     case STATE_READING_A:
       printf("STATE_READING_A\n");
       printf ("NEXT: %c\n", next);
       
       if (next == 'b') {
         state = STATE_READING_B;
       } else if (isAtEnd(next)) {
         state = STATE_ACCEPT;
       } else {
         state = STATE_REJECT;
       }
       break;
      
     case STATE_READING_B:
       printf("STATE_READING_B\n");
       printf ("NEXT: %c\n", next);
       
       if (next == 'a') {
         state = STATE_READING_A; 
       } else {
         state = STATE_REJECT;
       }
       break;

     case STATE_ACCEPT:
       printf ("Accept\n");       
       RUNNING = false;
       break;
      
     case STATE_REJECT:
       printf ("Reject\n");
       RUNNING = false;
       break;
    }
  }
  
  return 0;
  
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.