views:

651

answers:

3

I'm trying to write a CFG over the alphabet Σ = {a,b} for all words starting and ending with the same number of a's, with at least one b in the middle.

Now I understand the basic concept of CFG, variables, production rules, etc. Unfortunately I've run out of ideas for writing the aforementioned CFG. All I've got so far is

S → aYXYa
X → XbX | b | λ
Y → ???

I think that the production rules S and X will give me a string with two as on both sides with as many bs in the middle as I'd like. However, I'm not sure how I can also put as many as on both sides of the bs while making sure there are exactly the same number of as on each side.

Any suggestions, solutions would be much appreciated. Thanks.

+6  A: 

As an ex-professor who's taught this class before, I'm not going to give you the answer. I will, however, give you a hint:

You have the right idea to break it into two parts, the a's and the rest. However, you're not doing either one of them right.

First try writing: anban then branch off from there.

Hope that helps.

Brian Postow
Do you mean my rules should first accommodate as many balanced a's on either side before placing any b's in the middle?
Well, I meant you should write S = aSa | b first... then figure out the 2nd line... but yeah...
Brian Postow
+2  A: 
S → aSa | B
B → b | bB

This should be the CFG you're looking for. Whenever you've dealing with the same thing on the beginning and end, remember that you can't guarantee that the same var will be filled the same way. As such, you have to make those explicit.

DBendit
Thank you very much! Now I can finally move on. :)
Don't mention it. I'm having my own fun with Intro to Theoretical Computer Science (as my uni likes to call it)
DBendit
Haha. Wish you all the best! :)
A: 

It's been a while since my CS undergrad days but this looks reasonable:

S -> aSa | bX

X -> bX | E

Basically, you start with S and add as many pairs of a's as you want and then switch to X and add as many b's as you want.

David Archer
DBendit beat me by 6 seconds :)
David Archer
No worries, thank you for your answer as well. I've slightly modified both your solutions so that the start variable only accepts a's on both sides with an extra variable (a bit of repetition) to allow the addition of further a's and b's. :)