HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Is there a LL(1) grammar for the language with equal number of a's and b's?

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
thenumberwithequallanguagegrammarforandthere

Problem

Consider the following CFG.

$S \rightarrow \epsilon\ |\ aSbS\ |\ bSaS$

Can we prove formally that an equivalent $LL(1)$ grammar does not exist? I feel that intuitively an equivalent $LL(1)$ grammar doesn't exist, but I'm unable to prove this formally.

Solution

The language for the grammar in the question is the set of all words with equal number of $a$'s and $b$'s.

I am afraid your intuition is incorrect. Here is an $LL(1)$ grammar for the language.

$\qquad S \to AS \mid BS \mid \epsilon$

$\qquad A \to aXb$

$\qquad X \to AX \mid \epsilon$

$\qquad B \to bYa$

$\qquad Y \to BY \mid\epsilon$

Here is some statistics about the grammar above .
$$\begin{array} {|c|c|c|c|}
\hline
\text{nonterminal} &\text{first set} &\text{follow set} &\text{nullable} &\text{endable}\\\hline
S &a\ b &\emptyset &\text{yes} &\text{yes}\\\hline
A &a &a\ \ b &\text{no} &\text{yes}\\\hline
X &a &b &\text{yes} &\text{no} \\\hline
B &b &b\ \ a &\text{no} &\text{yes}\\\hline
Y &b &a &\text{yes} &\text{no} \\\hline
\end{array}$$

Here is the parsing table.
$$\begin{array} {|c|c|c|c|}\hline
&a &b &{\\\$} \\\hline
S &S\to AS &S\to BS &S\to \epsilon\\\hline
A &A\to aXb & & \\\hline
X &X\to AX &X\to\epsilon & \\\hline
B & &B\to bYa &\\\hline
Y &Y\to\epsilon &Y\to BY & \\\hline
\end{array}$$

Exercise 1. Show that both the grammar in the question and the grammar above generate the language of words with equal number of $a$'s and $b$'s.

Exercise 2. Consider the following grammar.

$\qquad S \to AS \mid BS \mid \epsilon$

$\qquad A \to aU$

$\qquad U \to AbA \mid b$

$\qquad B \to bV$

$\qquad V \to BaB \mid a$

Show that the grammar above also generate the language of words with equal number of $a$'s and $b$'s. Show that it is $LL(1)$.

Exercise 3. The following grammar also generate the language of equal number of $a$'s and $b$'s. Explain why it is not $LL(1)$.

$\qquad S \to AS \mid BS \mid \epsilon$

$\qquad A \to aAbA \mid \epsilon$

$\qquad B \to bBaB \mid \epsilon$

Context

StackExchange Computer Science Q#103628, answer score: 4

Revisions (0)

No revisions yet.