Construct context-free grammar with double restriction on amount of a's and b's?

492 Views Asked by At

Suppose language is defined $ \{a^nb^m|(m \neq n) and(m \neq 2n)\}$

Those amount of $b$'s can be anything, except same as amount of $a$s or twice as $a$s.

Can keep $m \neq n$. How to construct context-free grammar to keep both restrictions in place?

EDIT 1: Thanks Hans for comment. Lets divide into sections.

$S \rightarrow aA|Cb$

A handles where are more a's than b's. C - handles where are more than twice b's than a's.

$A \rightarrow aA|aAb|\epsilon$

$C \rightarrow aCbb|C_1$

$C_1 \rightarrow C_1b|b|\epsilon$

Ie we can have one b,additional b's, and for each additional b we can have exactly one a. We also can have one a for every two b's and additional b's.

How to do a's more than bs, but less than twice?

1

There are 1 best solutions below

1
On

Here is a hint: Strings of the form $a^nb^m$ for which $m\neq n$ and $m \neq 2n$ can be either

  • Strings for which $m < n$, or
  • Strings for which $m > n$, and $m < 2n$, or
  • Strings for which $m > n$, and $m > 2n$

Consider these three cases separately.