/* * Author : Kartik Kukreja * Description : Program to simulate a given NFA on an input string. It reads in the NFA from "NFA.txt" and the input strings from the console and prints out whether the strings are accepted or rejected on the console. "NFA.txt" must have the following format: N M F a1 a2 ... af T s1 y1 T1 t1 t2 ... tt1 s2 y2 T2 t1 t2 ... tt2 : : Here, N -> No. of states (states are numbered 0 ... N-1). 0 is the start state M -> Size of input alphabet (input symbols are numbered 1 ... M and 0 is reserved for epsilon) F -> No. of final states, followed by F states ( 0 <= ai <= N-1) T -> No. of transitions, followed by T lines si -> Previous state ( 0 <= si <= N-1) yi -> Input symbol or epsilon ( 0 <= yi <= M) Ti -> No. of states the NFA moves from si on input yi, followed by Ti states */ #include #include #include #include #include #include #define MAX_NFA_STATES 10 #define MAX_ALPHABET_SIZE 10 using namespace std; // Representation of an NFA state class NFAstate { public: int transitions[MAX_ALPHABET_SIZE][MAX_NFA_STATES]; NFAstate() { for(int i=0; i NFA_finalStates; bitset currentStates; char input_string[100000]; int N; // finds the epsilon closure of the NFA state "state" and stores it into "closure" void epsilonClosure(int state, bitset &closure ) { for(int i=0; i state, bitset &closure) { for(int i=0; i &Y) { for(int i=0; i X, int A, bitset &Y) { bitset tmp; for(int i=0; i> N >> M; NFAstates = new NFAstate[N]; fin >> F; for(i=0; i> X; NFA_finalStates.insert(X); } fin >> T; while(T--) { fin >> X >> A >> Y; for(i=0; i> j; NFAstates[X].transitions[A][i] = j; } } fin.close(); // simulate the NFA printf("Enter a string ('.' to exit) : "); scanf("%[^\n]%*c", input_string); while(input_string[0] != '.') { currentStates[0] = 1; epsilonClosure(currentStates, currentStates); p = strtok(input_string, " "); while(p) { symbol = atoi(p); if(symbol <= 0 || symbol > M) { printf("Invalid input symbol %d.\n", symbol); return -1; } else { NFAmove(currentStates, symbol, currentStates); epsilonClosure(currentStates, currentStates); } p = strtok(NULL, " "); } for(i = 0; i < N; i++) if(currentStates[i] == 1 && NFA_finalStates.find(i) != NFA_finalStates.end()) break; if(i < N) printf("String accepted.\n"); else printf("String rejected.\n"); printf("Enter a string ('.' to exit) : "); scanf("%[^\n]%*c", input_string); } return 0; }