Context Free Grammar for an Equal Number of a’s and b’s | CFG for an Equal Number of a’s and b’s

 Context Free Grammar  for an Equal Number of a’s   and  b’s | CFG for an Equal Number of a’s   and  b’s

×

×

×

OR
To construct a context-free grammar (CFG) for the language L={ww has an equal number of a’s and b’s}L = {w mid text{w has an equal number of } atext{‘s and } btext{‘s}}, we need a grammar that generates strings where the number of aa‘s and bb‘s are equal, without any specific order constraints.

CFG Construction

Here’s a CFG that generates such strings:

Start Symbol: SS

Production Rules:

SaSbbSaϵ

Explanation of the Rules:

1. :

  • This rule adds an aa to the beginning of the string and a bb to the end of the string, maintaining the balance of aa‘s and bb‘s. The string between these added aa and bb must also have an equal number of aa‘s and bb‘s, which is handled recursively by SS.
2. :
  • This rule is similar to the previous one but adds a bb to the beginning and an aa to the end. This also maintains the balance of aa‘s and bb‘s.
3. :
  • This rule allows for the empty string, which trivially has equal numbers of aa‘s and bb‘s (both counts are zero).
Example Derivations:

For the string aabbaabb:

  • SaSbS Rightarrow aSb
  • Now, SS must derive to something with equal aa‘s and bb‘s. Using SaSbS rightarrow aSb again:
    • SaSba(aSb)bS Rightarrow aSb Rightarrow a(aSb)b
    • Next, we need SϵS rightarrow epsilon:
      • SϵS Rightarrow epsilon
    • So, combining these, we get: aabaab + b=aabbb = aabb.

For the string abbaabba:

  • SaSbS Rightarrow aSb
  • For SS:
    • SbSaS Rightarrow bSa
    • Then SS must be ϵepsilon:
      • SϵS Rightarrow epsilon
    • So, combining these, we get: aa + bb + bb + a=abbaa = abba.
This CFG correctly generates all strings where the number of aa‘s equals the number of bb‘s.


Leave a Comment