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

Give a grammar for a language on Σ={a,b,c} that accepts all strings containing exactly one a

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

Problem

I have created the following solution but its left recursive:
S--> a|bSc|cSb|Sbc
Also it is not accepting:
"ab" or "cba" or "abb" or abc.

Somebody please guide me.

Zulfi.

Solution

Another way to arrive at a solution here - you might recognize that this language is regular, since, intuitively, you’d only need to remember whether you’d seen zero a’s, one a, or two or more a’s.

You can build a very simple two-state NFA for this regular language. The start state corresponds to having seen no a’s. It isn’t accepting and has a self-loop on b and c and a transition to a second state on a. That state corresponds to having seen one a, has self-loops on b and c, and dies off on seeing another a. (Note: I lack the LaTeXpertise to actually draw this automaton out. Please edit this answer if you know how to do that!)

Once you have this NFA, you can convert it into a CFG (more specifically, a right-linear grammar) as follows:

  • Create one nonterminal for each state.



  • For each transition from a state $Q$ to a state $R$ on character $x$, add the production rule $Q \to xR$.



  • For each accepting state $Q$, add a production $Q \to \varepsilon$.



This construction produces a CFG with the same language as the NFA - do you see why? And, in a cool twist, it produces the exact grammar given by @narekBoljikian in their answer! So you can think of that approach as what you’d get if you built an NFA and then turned it into a CFG.

Hope this helps!

Context

StackExchange Computer Science Q#117843, answer score: 4

Revisions (0)

No revisions yet.