2

I need to give a context-free grammar for each of the examples:

$L_1=\{a^hb^ka^mb^n : h+k=m+n\}$

$L_2=\{a^ib^ja^k : (i=j \,\,\,\, and \,\,\,\, k≥0) \,\,\,\, or \,\,\,\, (i\ge0 \,\,\,\, and \,\,\,\, j>k)\}$

I've done many simple examples and have improved on my skills to generate CFGs from grammars. I normally start off by solving for the simplest case, then building up from there. However, I'm confused as to where I can start to find the solutions to these problems.

Edit: This post has been marked as a duplicate and linking to here. However, my question is not about how to prove that a language is context free. It's about generating a context-free grammar from a given language.

JKawa
  • 21
  • 2
  • 1
    For the first language, start with a grammar for $x^ry^r$. The second is just a union of two context-free languages, which you can individually construct a grammar for. – Yuval Filmus Mar 31 '19 at 17:49
  • For the first language, it's pretty clear that $x^r y^r$ is $S \rightarrow xSy$. By this logic, I can decompose $x$ and $y$ to the following grammar: $S \rightarrow abSab$. Obviously, this isn't the correct full solution, so I assume that I have to add something in between each $a$ and $b$, say $A$. So the grammar now becomes $S \rightarrow aAbSaAb$. Now the question is how to derive $A$ since $a$ and $b$ are of different length both on the left ($h+k$) side and right side ($m+n$). – JKawa Mar 31 '19 at 19:24
  • In fact more is true: if $L_1,L_2$ are regular languages, then ${ xy : |x|=|y|, x \in L_1, y \in L_2 }$ is context-free. – Yuval Filmus Mar 31 '19 at 19:26
  • I don't understand this, $L_1$ and $L_2$ are independent numbers. Meaning that in the question that is given to me, $L_1$ is part a), and $L_2$ is part b). – JKawa Mar 31 '19 at 19:30
  • It's not your $L_1,L_2$. It's any $L_1,L_2$. Let me rephrase it: if $A,B$ are regular languages, then ${xy : |x|=|y|, x \in A, y \in B}$ is context-free. – Yuval Filmus Mar 31 '19 at 19:31
  • Got it, makes sense. So I would do $S \rightarrow ASA|\epsilon$ and $A \rightarrow a|b$ – JKawa Apr 01 '19 at 03:35
  • That won’t work. You have to guarantee that the result is in $a^b^a^b^$. – Yuval Filmus Apr 01 '19 at 04:32

0 Answers0