Unambiguous grammar for the language $S\to A|B, A\to B1|1B, B\to A0|0A|0$

42 Views Asked by At

I have the following context free grammar

$$ \begin{aligned} S &\to A \space | \space B \\ A &\to B1 \space | \space 1B \\ B &\to A0 \space | \space 0A \space | \space 0 \\ \end{aligned} $$

But it is ambiguous! Can we find an unambiguous grammar for the language generated by this grammar?

History

This comes from the age old question of trying to count "place to the start or to the end turn by turn" -sequences. I tried to use the Chomsky–Schützenberger Theorem to get the generating function for the counts. But for that the grammar needs to be unambiguous (it counts parse trees).

I tried an algorithm for removing left recursion from Compilers: Principles, Techniques, and Tools (4.19) and got

$$ \begin{aligned} S &\to A \space | \space B \\ A &\to B1 \space | \space 1B \\ B &\to 1B0C \space | \space 0AC \space | \space 0C \space | \space 1B0 \space | \space 0A \space | \space 0 \\ C &\to 10C \space | \space \varepsilon \end{aligned} $$

But this is still ambiguous... It looked promising as I got the generating function

$$\frac{2z+4z^2-z^3-2z^4}{1-7z^2+3z^4}$$

but this of course can't be correct.