2

I am struggling to construct a good CFG for a L={xE{0,1}* | that is of even length and have a maximum of two 0s}

So words like L={11, 10, 0011...}

I am trying with the following attempt.

S -> E | E0A | A0E | E0E0E | 00EA | EA00

E-> 1A | e

A -> 1E

I am running different derivations and they seem to make sense, but I am still unsure if my grammar is correct, or is there is a better way to improve it? Thank you very much, I have been struggling with CFG and I am trying to practice more to help me understand.

fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Demiah
  • 41
  • 8

3 Answers3

1

Your CFG does not appear to be correct since I do not see a derivation for 1001. Probably there are other issues with it.

We can begin with a CFG for the language of even-length strings of 0s and 1s:

S -> 0S0 | 0S1 | 1S0 | 1S1 | e

The only problem with this grammar is that it can produce two many 0s. We can avoid this by introducing new nonterminals after every production that adds a zero. Then, those other nonterminals can "remember" that we've seen the 0s already and have fewer valid productions. So...

S -> 0A0 | 0B1 | 1B0 | 1S1 | e
A -> 1A1 | e
B -> 0A1 | 1A0 | 1B1 | e

In this grammar, S represents having introduced no zeroes so far; A to having introduced both allowed zeroes; and B to having introduced just one.

Patrick87
  • 27,682
  • 3
  • 38
  • 73
1

Let X stand for "even number of 1s" and Y for "odd number of 1s".

You have 0, 1 or 2 zeroes, separating 1, 2 or 3 groups of 1s. These groups of ones, together with the zeroes, must have an even number of characters. Since every X has an even number of characters, we must have an even number of 0s and Ys.

Now write down all the possible cases.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
0

Another option here: the language you're describing here is regular. That means that you could...

  • ... write a regular expression for the language, then convert that into a CFG. There's a really nice way to do this - concatenations get preserved as concatenations, unions turn into different production options, and stars get rewritten in terms of a new nonterminal that expands to "any number of copies of the thing being starred."
  • ... design a DFA or NFA for the language, then convert it to a right-linear grammar. That is, make one nonterminal for each state. Add productions of the form A → bB for each transition in the automaton from state A to state B on the character b, then add productions of the form A → ε for each accepting state.

My suspicion is that the second of these options will give you a fairly straightforward CFG with a manageable number of nonterminals. Specifically, form the DFA as the cross product of a simple DFA that counts the number of 0s and a simple DFA that tracks parity, then convert that to a CFG.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065