0

I need to find a context free grammar for the following language:

L= { w from { a,b,c,d }* : #a+2#b=2#c+#d }

Here is my attempt, but I doubt it is correct:

S -> aSd|dSa|BSC|CSB|abSdc|baScd|dcSab|cdSba|SS|λ
B -> c|dd
C -> b|aa 
m0s
  • 4,250
  • 9
  • 41
  • 64
  • Why is there a lambda in your grammar? Is that the same as an ε-production (empty-string)? – DaoWen Mar 25 '14 at 04:43
  • @DaoWen Yes λ is same as ε – m0s Mar 25 '14 at 04:45
  • I'm sure you can construct a CFG for _a_ language that has that property—but I'm pretty sure it's impossible to generate that exact language with a CFG. For example, how can you generate `aacbdd`? – DaoWen Mar 25 '14 at 04:55
  • @DaoWen I am confused, do you mean the language is not context free, or do you mean my CFG isn't right for the language? For 'aacbdd' using the grammar I have there I think I can do S=>aSd=>aaSdd=>aaBSCdd=>aacSbdd=>aacbdd – m0s Mar 25 '14 at 05:16
  • I meant that I don't think the language is context free. Using your current grammar you can also generate S -> aSd -> ad, which isn't supposed to be in the language. You have to count too many things in this language for it to be context-free. There's no way you can maintain the #a+2#b=2#c+#d relationship with just the stack of a [PDA](http://en.wikipedia.org/wiki/Pushdown_automaton#PDA_and_Context-free_Languages). – DaoWen Mar 25 '14 at 05:19
  • @DaoWen Why 'ad' is in the language for sure. I hope the notation isn't confusing, by #a I mean number of a's in the word and so on. I wasn't able to apply the pumping lemma to show it isn't context free, which would be a satisfying answer. – m0s Mar 25 '14 at 06:06
  • You're right, I was confused. In that case, you should also be able to generate `cb` and `aaccaa`. – DaoWen Mar 25 '14 at 06:16

1 Answers1

1

You can construct a PDA that recognizes the language like this:

  • The characters a and b in the input correspond to a on the stack.
  • The characters c and d correspond to c on the stack.
  • If the stack is empty or the top is a, and a is on the input, consume it and push a to the stack.
  • If the stack is empty or the top is a, and b is on the input, consume it and push aa to the stack.
  • If the stack is empty or the top is c, and c is on the input, consume it and push cc to the stack.
  • If the stack is empty or the top is c, and d is on the input, consume it and push c to the stack.
  • If the stack top is c and a is on the input, consume a and pop the c.
  • If the stack top is c and b is on the input, consume b and pop the c, moving to a special state that either pop another c or pushes an a if the stack is empty.
  • ...
  • The accept state is where both the input and stack are empty.

That means you must be able to construct a CFG. I think you're on the right track, but this CFG is going to be a pain to write since there are no ordering constraints. This means you'll have a lot of permutations of the same basic rule.

DaoWen
  • 32,589
  • 6
  • 74
  • 101