Created
October 6, 2017 15:34
-
-
Save marty1885/74fac504517e4df2ef1fe2b0f57d2905 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#define OP_STATE 0 | |
#define NUM_STATE 1 | |
#define FBRAC_STATE 2 | |
#define BBRAC_STATE 3 | |
typedef void(*TransFunc)(int*, char); | |
typedef struct | |
{ | |
int state; | |
TransFunc* fptrs; | |
int numStates; | |
} StateMachine; | |
int bracDepth = 0; | |
int isOp(char ch) | |
{ | |
if(ch == '+' || ch == '-' || ch == '*' || ch=='/') | |
return 1; | |
return 0; | |
} | |
StateMachine* makeStateMachine(int numStates) | |
{ | |
StateMachine* sm = (StateMachine*)malloc(sizeof(StateMachine)); | |
sm->fptrs = (TransFunc*)malloc(numStates*sizeof(TransFunc)); | |
sm->numStates = numStates; | |
sm->state = 0; | |
return sm; | |
} | |
void setStateMachineTransFunc(StateMachine* sm, int state, TransFunc func) | |
{ | |
TransFunc* ptr = &sm->fptrs[state]; | |
*ptr = func; | |
} | |
void runStateMachine(StateMachine* sm, int input) | |
{ | |
int state = sm->state; | |
sm->fptrs[state](&sm->state, input); | |
//printf("%c, %d\n",(char)input, sm->state); | |
if(sm->state < 0 || sm->state >= sm->numStates) | |
{ | |
printf("Sequence not legal\n"); | |
exit(0); | |
} | |
} | |
void OpStateTransitionFunction(int* state, char ch) | |
{ | |
if(ch == ')' || isOp(ch)) | |
*state = -1; | |
else if(ch == '(') | |
{ | |
*state = FBRAC_STATE; | |
bracDepth++; | |
} | |
else | |
*state = NUM_STATE; | |
} | |
void NumStateTransitionFunction(int* state, char ch) | |
{ | |
if(ch == '(') | |
*state = -1; | |
else if(ch == ')') | |
{ | |
*state = BBRAC_STATE; | |
bracDepth--; | |
} | |
else if(isOp(ch)) | |
*state = OP_STATE; | |
else | |
*state = NUM_STATE; | |
} | |
void FBracStateTransitionFunction(int* state, char ch) | |
{ | |
OpStateTransitionFunction(state, ch); | |
} | |
void BBracStateTransitionFunction(int* state, char ch) | |
{ | |
NumStateTransitionFunction(state, ch); | |
} | |
int main() | |
{ | |
char str[40] = {0}; | |
StateMachine* sm = makeStateMachine(4); | |
bracDepth = 0; | |
setStateMachineTransFunc(sm,OP_STATE,OpStateTransitionFunction); | |
setStateMachineTransFunc(sm,NUM_STATE,NumStateTransitionFunction); | |
setStateMachineTransFunc(sm,FBRAC_STATE,FBracStateTransitionFunction); | |
setStateMachineTransFunc(sm,BBRAC_STATE,BBracStateTransitionFunction); | |
scanf("%s",str); | |
int size = strlen(str); | |
for(int i=0;i<size;i++) | |
{ | |
char ch = str[i]; | |
runStateMachine(sm, ch); | |
} | |
if(bracDepth != 0) | |
printf("Sequence not legal\n"); | |
else | |
printf("Sequence is goof"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment