-2

Provide a context-free grammar that generates the following language over

Σ = {0,1}: {w = 0*1* : |w| is odd}

My Solution:

S->AB|0|1

A->0A|^

B->1B|^

But using this grammar we are able to create an even number of string.

I want grammar that produces L = {0,1,000,111,001,011,00000,11111,00001,00011....}

rici
  • 234,347
  • 28
  • 237
  • 341
Parth Patel
  • 125
  • 4
  • 16

1 Answers1

3

An odd number is the sum of an odd number and an even number, so sentences in the language are either an odd number of 0s followed by an even number of 1s, or an even number of 0s followed by an odd number of ones. Moreover, an odd number is an even number plus one; if we make that substitution in the preceding description we get "an even number of 0s followed by either 0 or 1, followed by an even number of 1s". Since every even number is either 0 or two more than an even number, we end up with.

S -> A 0 B | A 1 B
A -> ε | A 0 0
B -> ε | B 1 1

or

S -> 0 | 1 | 0 0 S | S 1 1
rici
  • 234,347
  • 28
  • 237
  • 341
  • Thank you for an explanation. I spend an hour to solve this question. – Parth Patel Nov 29 '16 at 08:17
  • That is still missing some cases for odd length strings. For example, 010 is odd length but cannot be derived from S. You can add two more productions to your grammar and it will be perfect. Updating the second grammar, the correct answer would be: S -> 0 | 1 | 00S | 01S | 10S | 11S – Hazem Nov 23 '19 at 19:42
  • 1
    @hazem: `010` is not in `0*1*`, so it is not in the desired language. We're not just looking for odd-length strings. – rici Nov 23 '19 at 20:09
  • I see what you mean. Actually, the question (now closed) was formulated badly. In the title, it says: "odd length language". Since I rejected the idea he could be looking for a finite language with an odd number of strings, I assumed he meant a language with stings of odd length. But then, it mentions the {0*1*} thing. So I assumed that was an error and the author meant w \in {0, 1}* but could not express it correctly. I even went to the extreme to edit the question itself the way I understood it. Maybe I should retract the edit (and my comment?) – Hazem Nov 23 '19 at 20:55
  • @hazem: I rolled back the edit, which would never gave made it through an edit review. Aside from anything else, the fact that OP accepted my answer is pretty good evidence that my interpretation of the question was correct. – rici Nov 24 '19 at 06:37
  • @rici Perfect. No problem. Would you like to keep this discussion (to give more insight how *not* to solve the problem, in particular, your 00S and S11 with the variable on different sides vs. my 00S and 11S on one side for the wrong answer). Or if you prefer, I can delete all my comments to avoid confusion? I am open both ways. – Hazem Nov 24 '19 at 07:38