I've been trying create a formal language for the following $L=\{w\in\{a,b\}∗ | \#ab(w) = \#ba(w) \}$.
First I've tried to do the following:
$S \to abSba | baSab | A | B| \mathcal E$
$A \to aA | Bb$
$B \to Ca$
$C \to \mathcal E$
But that solution isn't good as for example while I can output "$abbbbba$", but the opposite "$abaaaaaba$" is not possible.
And if I'll more variables for adding a's from the right the whole thing will become a complete mass.
I would be really glad to know where I'm doing wrong towards solving it and how should I approach in order to solve it.
Consider the following grammar that accepts words over the alphabet $ \{a,b\}^{*}$ that have an equal number of sequence of $ab$ as of $ba$. (Examples of words accepted are $\epsilon, aba, bab, aaa, bbabbb, abaabaaa$)
$ S \rightarrow a A_0 \ |\ b B_0 \ |\ \epsilon $
$ A_0 \rightarrow a A_0\ |\ bA_1 \ |\ \epsilon $
$ B_0 \rightarrow b B_0\ |\ aB_1 \ |\ \epsilon $
$ A_1 \rightarrow b A_1\ |\ a A_0 $
$ B_1 \rightarrow a B_1\ |\ b B_0 $
When you're in state $A_0$ you can add $a$'s (doesn't change the amount of $ab$ or $ba$) and you can finish your word at any moment. If you choose to add another $b$, i.e., increasing the sequence $ab$ by one you go to state $A_1$ in which you will have eventually to add one $a$.