Context Free Grammar (CFG) for Un-Equal numbers of a’s and b’s | CFG for Un-Equal numbers of a’s and b’s

 Context Free Grammar (CFG) for Un-Equal numbers of a’s   and  b’s |  CFG for Un-Equal numbers of a’s   and  b’s

×

×

×

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

CFG Construction

We’ll approach this by constructing a CFG that generates strings where:

  1. The number of aa‘s is greater than the number of bb‘s.
  2. The number of bb‘s is greater than the number of aa‘s.

Here’s a CFG that generates such strings:

  1. Start Symbol: SS
  2. Production Rules:
    • SaSbbSaaSSbabS rightarrow aSb mid bSa mid aS mid Sb mid a mid b

Explanation of the Rules:

  1. SaSbS rightarrow aSb:

    • This rule adds an aa to the beginning and a bb to the end, ensuring that the number of aa‘s and bb‘s are not equal by recursively ensuring the mismatch continues in the middle.
  2. SbSaS rightarrow bSa:

    • This rule adds a bb to the beginning and an aa to the end, ensuring the same kind of imbalance but starting with more bb‘s than aa‘s.
  3. SaSS rightarrow aS:

    • This rule ensures that adding extra aa‘s while the substring SS can have any valid imbalance, thus guaranteeing more aa‘s than bb‘s.
  4. SSbS rightarrow Sb:

    • This rule ensures that adding extra bb‘s while the substring SS can have any valid imbalance, thus guaranteeing more bb‘s than aa‘s.
  5. SabS rightarrow a mid b:

    • These rules cover the cases where there is only one aa or bb, which automatically implies an imbalance.

Example Derivations:

  • For the string aaabaaab:

    • Start with SaSbS rightarrow aSb
    • To make SaSS rightarrow aS:
      • Sa(aSb)bS rightarrow a(aSb)b
      • Continue with SaS rightarrow a:
        • Sa(a(ab))baaabS rightarrow a(a(a mid b))b rightarrow aaab
  • For the string bb:

    • Start with SSbS rightarrow Sb:
      • SbS rightarrow b
    • Combining these gives bbbb.
  • For the string aabaab

    • Start with SaSbS rightarrow aSb:
      • Sa(ab)aabS rightarrow a(a mid b) rightarrow aab

This CFG effectively generates strings where the number of aa‘s is not equal to the number of bb‘s.

Leave a Comment