Advertisement
Coder_22

First and Follow

Jan 4th, 2025
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int N = 26;
  4.  
  5. int main() {
  6.     cout << "Enter the number of production rules: ";
  7.     int t;
  8.     cin >> t;
  9.     string pro[t];
  10.     set<char> first[N], follow[N];
  11.     vector<int> con[N], con2[N];
  12.     cout << "Enter the production rules: ";
  13.     for (int i = 0; i < t; ++i) {
  14.         string s;
  15.         cin >> s;
  16.         pro[i] = s;
  17.         int n = s.size();
  18.         for (int j = 0; j < n - 1; ++j) {
  19.             if (islower(s[j]) and isupper(s[j + 1])) first[s[0] - 'A'].insert(s[j]);
  20.             if (islower(s[j + 1]) and isalpha(s[j])) follow[s[0] - 'A'].insert(s[j + 1]);
  21.             if (isupper(s[j]) and s[j + 1] == '|') con[s[0] - 'A'].push_back(s[j] - 'A');
  22.         }
  23.         if (s[n - 1] == '@' and s[n - 2] == '|')
  24.             first[s[0] - 'A'].insert(s[n - 1]);
  25.         else if (isupper(s[n - 1]))
  26.             con2[s[0] - 'A'].push_back(s[n - 1] - 'A');
  27.     }
  28.     for (int i = 0; i < N; ++i) {
  29.         for (auto ele : con[i])
  30.             for (auto e : first[ele]) first[i].insert(e);
  31.         for (auto ele : con2[i])
  32.             for (auto e : follow[ele]) follow[i].insert(e);
  33.     }
  34.     cout << "Productions\tFirst\tFollow\n";
  35.     for (int i = 0; i < t; ++i) {
  36.         cout << pro[i] << '\t';
  37.         if (!first[pro[i][0] - 'A'].empty()) {
  38.             for (auto e : first[pro[i][0] - 'A']) cout << e << ' ';
  39.             cout << '\t';
  40.         }
  41.         cout << '@' << ' ';
  42.         if (!follow[pro[i][0] - 'A'].empty()) {
  43.             for (auto e : follow[pro[i][0] - 'A']) cout << e << ' ';
  44.             cout << '\n';
  45.         }
  46.     }
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement