-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExp7.cpp
136 lines (120 loc) · 2.83 KB
/
Exp7.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Write a program to find FIRST set for any given grammar
// input is from a file
// Rules for input file:
// (1) Use e for epsilon
// (2) No white spaces except newline for new production
// (3) The first symbol should be start symbol
// (4) Capital letters for non-terminals and small letters for terminals except e.
// Sample input:
// S->ACB|CbB|Ba
// A->da|BC
// B->g|e
// C->h|e
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
#include <map>
using namespace std;
pair<char, map<char, vector<vector<char>>>> readFile()
{
char startSymbol;
map<char, vector<vector<char>>> productionsMap;
ifstream fin("Exp7input.txt");
string str;
bool flag = 0;
cout << "Grammar: " << '\n';
while (getline(fin, str))
{
if (flag == 0)
startSymbol = str[0], flag = 1;
cout << str << '\n';
vector<char> temp;
char s = str[0];
for (int i = 3; i < str.size(); i++)
{
if (str[i] == '|')
{
productionsMap[s].push_back(temp);
temp.clear();
}
else
temp.push_back(str[i]);
}
productionsMap[s].push_back(temp);
}
return {startSymbol, productionsMap};
}
bool dfs(char i, char org, char last, map<char, vector<vector<char>>> &productionsMap, set<char> &firstSet)
{
bool rtake = false;
for (auto str : productionsMap[i])
{
bool take = true;
for (char c : str)
{
if (c == i || !take)
break;
if (!(c >= 'A' && c <= 'Z') && c != 'e')
{
// for terminal
firstSet.insert(c);
break;
}
else if (c == 'e')
{
// for epsilon
if (org == i || i == last)
firstSet.insert(c);
rtake = true;
break;
}
else
{
// for non-terminal
take = dfs(c, org, str[str.size() - 1], productionsMap, firstSet);
rtake |= take;
}
}
}
return rtake;
}
void findFIRST(map<char, set<char>> &firstResult,
map<char, vector<vector<char>>> &productionsMap)
{
for (auto p : productionsMap)
{
char c = p.first;
set<char> firstSet;
dfs(c, c, c, productionsMap, firstSet);
for (auto t : firstSet)
firstResult[c].insert(t);
}
}
void printFIRST(map<char, set<char>> &mp)
{
for (auto p : mp)
{
string ans = "";
ans += p.first;
ans += " = {";
for (char r : p.second)
{
ans += r;
ans += ',';
}
ans.pop_back();
ans += "}";
cout << ans << '\n';
}
}
int main()
{
auto p = readFile();
char startSymbol = p.first;
map<char, vector<vector<char>>> productionsMap = p.second;
map<char, set<char>> firstResult;
findFIRST(firstResult, productionsMap);
cout << "\nFIRST: " << '\n';
printFIRST(firstResult);
}