Constructing context free grammar with a number constraint to one of the elements in the language

106 Views Asked by At

How do I determine the rules of a context free grammar when there is a constraint on one of the elements?

For example over the alphabet {0, 1} containing all words with at most three 1s?

I have the following but seems the production rules could be much more succinct, any ideas?

 S -> X1X1X1X
 S -> X1X1X
 S -> X1X
 S -> X
 X -> 0X
 X -> e

e is epsilon

1

There are 1 best solutions below

0
On

For regular languages like these, I like to imagine reading the string from left to right and keeping track of how many ones I've seen so far. Let the symbols $A,B,C,D$ represent a state where you've seen zero, one, two, or three 1s so far.

Then a grammar for your language is:

\begin{align*} A &\mapsto \epsilon \;|\; 0A \;|\; 1B \\ B &\mapsto \epsilon \;|\; 0B \;|\; 1C \\ C &\mapsto \epsilon \;|\; 0C \;|\; 1D \\ D &\mapsto \epsilon \;|\; 0D \end{align*}