简体   繁体   中英

Constructing CFG for even length words with maximum of two 0's

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.

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.

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM