0% found this document useful (0 votes)
12 views4 pages

Remove Left Recursion in Grammar

Uploaded by

diveshanand8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views4 pages

Remove Left Recursion in Grammar

Uploaded by

diveshanand8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Aim-WAP to estimate left recursion from the given

grammar
Code-
#include <bits/stdc++.h>

using namespace std;

void eliminateImmediateLR(char A, vector<string> &prods, map<char, vector<string>> &grammar) {

vector<string> alpha, beta;

for (auto &prod : prods) {

if (prod[0] == A) {

alpha.push_back([Link](1));

} else {

beta.push_back(prod);

if ([Link]()) {

grammar[A] = prods;

return;

char newNT = A + 39;

vector<string> newA, newAprime;

for (auto &b : beta) {

newA.push_back(b + newNT);
}

for (auto &a : alpha) {

newAprime.push_back(a + newNT);

newAprime.push_back("#");

grammar[A] = newA;

grammar[newNT] = newAprime;

void eliminateLeftRecursion(vector<char> order, map<char, vector<string>> &grammar) {

int n = [Link]();

for (int i = 0; i < n; i++) {

char Ai = order[i];

for (int j = 0; j < i; j++) {

char Aj = order[j];

vector<string> newProds;

for (auto &prod : grammar[Ai]) {

if (prod[0] == Aj) {

for (auto &delta : grammar[Aj]) {

newProds.push_back(delta + [Link](1));

} else {

newProds.push_back(prod);

}
grammar[Ai] = newProds;

eliminateImmediateLR(Ai, grammar[Ai], grammar);

void printGrammar(map<char, vector<string>> &grammar) {

for (auto &rule : grammar) {

cout << [Link] << " -> ";

for (int i = 0; i < [Link](); i++) {

cout << [Link][i];

if (i != [Link]() - 1) cout << " | ";

cout << endl;

int main() {

// Example grammar:

// S -> Aa | b

// A -> Sc | d

map<char, vector<string>> grammar;

grammar['S'] = {"Aa", "b"};

grammar['A'] = {"Sc", "d"};

vector<char> order = {'S', 'A'};

cout << "Original Grammar:\n";

printGrammar(grammar);
cout << "\nAfter removing left recursion:\n";

eliminateLeftRecursion(order, grammar);

printGrammar(grammar);

return 0;

Output-

You might also like