-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExp1.cpp
105 lines (85 loc) · 1.87 KB
/
Exp1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Write a program to design Finite Automata that accepts all strings ending with “ing”, over ∑= a to z. (example “anything”, “something”, “nothing”, etc.)
#include<iostream>
#include<vector>
using namespace std;
class DFA
{
int numOfStates;
vector<char>alphabet;
int initialState;
int finalState;
vector<vector<int>>transitionFn;
public:
DFA()
{
numOfStates = 4;
initialState = 0;
finalState = 3;
constructTransitionFn();
}
void constructTransitionFn()
{
// Starting with q0
transitionFn = vector<vector<int>>(numOfStates, vector<int>(26, -1));
transitionFn[0]['i'-'a'] = 1;
for (int i = 0; i < 26; i++)
{
if(i == ('i'-'a'))
continue;
transitionFn[0][i] = 0;
}
// Starting with q1
transitionFn[1]['i'-'a'] = 1;
transitionFn[1]['n'-'a'] = 2;
for (int i = 0; i < 26; i++)
{
if(i == ('i'-'a') or i == ('n'-'a'))
continue;
transitionFn[1][i] = 0;
}
// Starting with q2
transitionFn[2]['i'-'a'] = 1;
transitionFn[2]['g'-'a'] = 3;
for (int i = 0; i < 26; i++)
{
if(i == ('i'-'a') or i == ('g'-'a'))
continue;
transitionFn[2][i] = 0;
}
// Starting with q3
transitionFn[3]['i'-'a'] = 1;
for (int i = 0; i < 26; i++)
{
if(i == ('i'-'a'))
continue;
transitionFn[3][i] = 0;
}
}
bool accepts(string str)
{
int currState = initialState;
for(char c:str)
{
currState = transitionFn[currState][c-'a'];
}
return currState == finalState;
}
};
int main()
{
cout<<"DFA to accept all strings ending with 'ing'\n\n";
DFA fa;
string str;
while(true)
{
cout<<"Enter string (# to stop): ";
cin>>str;
if(str=="#")
break;
bool b = fa.accepts(str);
if(b)
cout<<"Accepted"<<endl<<endl;
else
cout<<"Not accepted"<<endl<<endl;
}
}