Question

How can I construct a context free grammar for the following language:

L = {a^l b^m c^n d^p   | l+n==m+p; l,m,n,p >=1}

I started by attempting:

S -> abcd | aAbBcd | abcCdD | aAbcdD | AabBcCd

and then A = something else... but I couldn't get this working.

.

I was wondering how can we remember how many c's shud be increased for the no. of b's increased?
For example:

string : abbccd
Was it helpful?

Solution

The grammar is :

  1. S1 -> a S1 d | S2

  2. S2 -> S3 S4

  3. S3 -> a S3 b | epsilon

  4. S4 -> S5 S6

  5. S5 -> b S5 c | epsilon

  6. S6 -> c S6 d | epsilon

Rule 1 adds equal number of a's and d's.

Rule 3 adds equal number of a's and b's.

Rule 5 adds equal number of b's and c's.

Rule 6 adds equal number of c's and d's

The rules also ensure that the ordering of the alphabets are maintained according to the language given.

OTHER TIPS

How's about this:

S1 -> a S2 d                   # at least one a and d
S2 -> a S2 d
S2 -> S3 S4                    # no more d, split into ab and bc parts
S2 -> S4 S5                    # no more a, split into bc and cd parts

S3 -> a S3 b
S3 ->                          # already ensured at least one a and b
S4 -> b S4 c                  
S4 -> b c                      # at least one b and c
S5 -> c S5 d   
S5 ->                          # already ensured at least one c and d

The key to this is how you group... (i.e. "parts" rather than non-terminals.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top