This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Context-Free Languages Sample Solutions Designing CFLs Problem 1: Give a context-free grammar that generates the following language over f ; g £ : = f Û j Û contains more 1s than 0s g Solution: Idea: this is similar to the language where the number of 0s is equal to the number of 1s, except we must ensure that we generate at least one 1, and we must allow an arbitrary number of 1s to be generated anywhere in the derivation. The following grammar accomplishes this task: ! ! j j jj ¯ Proof of correctness: it should be clear that this grammar cannot generate any strings not in . The production for guarrantees that any string contains at least one 1, and any time a 0 is generated, at least one additional 1 is generated with it. We must argue that the grammar generates all strings with more 1s than 0s. The productions for generate all strings containing a number of 1s greater than or equal to the number of 0s (proven below). The production for asserts that any string Þ in can be written Þ = ÜÝ where Ü Ü and Ý Ý . This is true: if Þ begins with a 1, we can say that Þ = ¯Ý . If Þ begins with a 0, we can use a counter which is incremented by 1 for each 0 encountered and decremented by 1 for each 1 encountered, and at some point in the string this counter must become -1 upon encountering a 1 since Þ contains more 1s than 0s. Let the part of Þ prior to this point be Ü and the part of Þ after this point be Ý ; clearly, this breakdown of Þ = ÜÝ satisfies the requirements stated above. Now, to show that generates all strings Þ such that Þ Þ , the same “counter” argument will work. If Þ begins with a 0, it must be of the form Þ = ÜÝ where Ü = Ü and Ý Ý . If, on the other hand, Þ begins with a 1, it must either be the case that Þ = ÜÝ where Ü = Ü and Ý Ý , or it is the case that Þ = Ü where Ü Ü . Both of these cases are handled by the transitions. 1 Problem 2: Give a context-free grammar generating the language = the complement of the language f a Ò b Ò j Ò g : Solution: Idea: we can break this language into the union of several simpler languages: = f a i b j j i> j g[ f a i b j j i< j g[ a [ b £ b a [ b £ a a [ b £ . That is, all strings of a’s followed by b’s in which the number of a’s and b’s differ, unioned with all strings not of the form a i b j . First, we can achieve the union of the CFGs for the three languages: ! jj Now, the set of strings f a i b j j i> j g is generated by a simple CFG: ! ab j a j a Similarly for f a i b j j i< j g : ! ab j b j b Finally, a [ b £ b a [ b £ a a [ b £ is easily generated as follows: ! X bX aX X ! a j b Problem 3: Give a CFG to generate A = f a i b jk j i ;j ;k and either i = j or j = k g : Is the grammar ambiguous? Why or why not?...
View Full Document
This note was uploaded on 01/06/2012 for the course COMPUTER S 123432 taught by Professor Cool during the Three '09 term at ADFA.
- Three '09