Find context-free grammar for the following language (with n≥0 and m≥0): L={w∈{a,b}*: n_a≠n_b}
Assume: n_a=n_b
S-> SS | aSb | bSa | λ
Add a’s or add b’s S-> SS | aSb | bSa | aS | bS | a | b
Find context-free grammar for the following language (with n≥0 and m≥0): L={w∈{a,b}*: n_a≠n_b}
Assume: n_a=n_b
S-> SS | aSb | bSa | λ
Add a’s or add b’s S-> SS | aSb | bSa | aS | bS | a | b
If the number of a is different from the number of b, then either there are more a or more b. We can handle these cases separately. Let's handle the case of more a first. To ensure there are more a than b, we can start with an equal number of a and b and make some changes.
S -> e | Sab | Sba | aSb | bSa | abS | baS
That should be a grammar that gives us exactly the strings with the same number of a and b. Why do I think that? It covers all arrangements of adding one a and one b at a time, so it probably works. Exercise: prove it.
Next, we want to allow adding more a. We can be dumb about it and just introduce a new symbol that gives us a* and intersperse it in all our productions:
S -> A | ASAaAbA | ASAbAaA | AaASAbA | AbASAaA | AaAbASA | AbAaASA
A -> Aa | a
We can do the same thing for the case of more B:
S -> B | BSBaBbB | BSBbBaB | BaBSBbB | BbBSBaB | BaBbBSB | BbBaBSB
B -> Bb | b
Getting an answer now is as simply as combining:
S -> A | ASAaAbA | ASAbAaA | AaASAbA | AbASAaA | AaAbASA | AbAaASA
S -> B | BSBaBbB | BSBbBaB | BaBSBbB | BbBSBaB | BaBbBSB | BbBaBSB
A -> a | Aa
B -> b | Bb
EDIT - as pointed out by Welbog in the comments, this misses some strings because A and B don't derive a* and b* but a+ and b+, so we're forcing the addition of more a and b than we actually need in some cases. A perhaps less than horrible way to resolve this problem is to change A and B to derive a* and b* and then simply insert a and b along with the A and B on exactly one of the A and B in each production. This will force that there be at least one more a/b and allow arbitrarily more without requiring multiple additional instances, as the grammar above does. So:
S -> Aa | AaSAaAbA | AaSAbAaA | AaaASAbA | AabASAaA | AaaAbASA | AabAaASA
| ASAaaAbA | ASAabAaA | AaAaSAbA | AbAaSAaA | AaAabASA | AbAaaASA
| ASAaAabA | ASAbAaaA | AaASAabA | AbASAaaA | AaAbAaSA | AbAaAaSA
| ASAaAbAa | ASAbAaAa | AaASAbAa | AbASAaAa | AaAbASAa | AbAaASAa
S -> Bb | BbSBaBbB | BbSBbBaB | BbaBSBbB | BbbBSBaB | BbaBbBSB | BbbBaBSB
| BSBbaBbB | BSBbbBaB | BaBbSBbB | BbBbSBaB | BaBbbBSB | BbBbaBSB
| BSBaBbbB | BSBbBbaB | BaBSBbbB | BbBSBbaB | BaBbBbSB | BbBaBbSB
| BSBaBbBb | BSBbBaBb | BaBSBbBb | BbBSBaBb | BaBbBSBb | BbBaBSBb
A -> e | Aa
B -> e | Bb
Some of those productions are probably unnecessary, but the grammar should work.