#include #include int main(int argc, char* argv[]) { char* stack; int sCount = 0; char next; char* input; int iCount = 0; int state = 0; if ((stack = malloc(sizeof(input)*sizeof(int))) == NULL) { exit(EXIT_FAILURE); } /* This bit catches the empty string. */ if (argc == 1) { printf("The empty string is accepted!\n"); exit(0); } input = argv[1]; next = input[iCount]; /* printf("%s\n", argv[1]); */ if ((state == 0)) { state = 1; stack[sCount] = '$'; } /* The rest of this loops through the various transition rules until there is no more input and nothing on the stack, or there is no rule for the current situation. If there is no rule, the machine rejects. */ while((next != '\0')||((stack[sCount] == '$')||(stack[sCount] == '1'))) { /* printf("%d:%c:%c\n", state, next, stack[sCount]); */ if ((state == 1)&&(next == 'a')) { state = 1; iCount++; next = input[iCount]; sCount++; stack[sCount] = '1'; } else if ((state == 1)&&(next == 'b')) { state = 2; iCount++; next = input[iCount]; sCount++; stack[sCount] = '1'; } else if ((state == 1)&&(next == 'c')&&(stack[sCount] == '1')) { state = 3; iCount++; next = input[iCount]; stack[sCount] = '\0'; sCount--; } else if ((state == 2)&&(next == 'b')) { state = 2; iCount++; next = input[iCount]; sCount++; stack[sCount] = '1'; } else if ((state == 2)&&(next == 'c')&&(stack[sCount] == '1')) { state = 3; iCount++; next = input[iCount]; stack[sCount] = '\0'; sCount--; } else if ((state == 3)&&(next == 'c')&&(stack[sCount] == '1')) { state = 3; iCount++; next = input[iCount]; stack[sCount] = '\0'; sCount--; } else if ((state == 3)&&(stack[sCount] == '$')) { state = 4; stack[sCount] = '\0'; sCount--; } else { printf("%s is rejected.\n", argv[1]); exit(0); } } /* If there is no more input and nothing on the stack, but the machine is in an accept state, the machine accepts. Otherwise, it rejects. */ if (state == 4) { printf("%s is accepted!\n", argv[1]); } else { printf("%s is rejected.\n", argv[1]); } return 0; }