context-free-grammarautomatapushdown-automaton

How do I get the context free grammar of this language?


With this language:

L = {x^i, y^j, z^k : i != j ∨ j != k; i ≥ 0; j ≥ 0; k ≥ 0}, Σ = {x, y, z}

How do I get the context-free grammar of this language?


Solution

  • There are some tricks that can be used to solve problems like this, and this problem benefits from at least a couple of them:

    1. Always split languages based on unions and logical "or". In this case, our language L = {x^i, y^j, z^k : i != j ∨ j != k; i ≥ 0; j ≥ 0; k ≥ 0} has a logical "or" in the condition and is therefore equivalent to the union of two languages with the condition split: L = L1 U L2 where L1 = {x^i, y^j, z^k : i != j; i ≥ 0; j ≥ 0; k ≥ 0} and L2 = {x^i, y^j, z^k : j != k; i ≥ 0; j ≥ 0; k ≥ 0}. A CFG for the union of two CFLs can be formed by introducing a new start nonterminal that produces each of the start nonterminals for the CFLs' CFGs.

    2. Rewrite complicated conditions as equivalent expressions involving simple conditions, ideally ones for which you already know how to write the CFG. For instance, i != j is equivalent to i < j ∨ i > j. This allows us to rewrite L1 and L2 from above as L1 = {x^i, y^j, z^k : i < j ∨ i > j; i ≥ 0; j ≥ 0; k ≥ 0} and L2 = {x^i, y^j, z^k : j < k ∨ j > k; i ≥ 0; j ≥ 0; k ≥ 0}. Notice that we can now rewrite L1 = L3 U L4 and L2 = L5 U L6 using the consideration from above, so L = L3 U L4 U L5 U L6 where L3 = {x^i, y^j, z^k : i < j; i ≥ 0; j ≥ 0; k ≥ 0}, L4 = {x^i, y^j, z^k : i > j; i ≥ 0; j ≥ 0; k ≥ 0}, L5 = {x^i, y^j, z^k : j < k; i ≥ 0; j ≥ 0; k ≥ 0} and L6 = {x^i, y^j, z^k : j > k; i ≥ 0; j ≥ 0; k ≥ 0}.

    CFGs for these are a little easier to produce:

    S3 := S3 z | T3
    T3 := x T3 y | T3 y | y
    
    S4 := S4 z | T4
    T4 := x T4 y | x T4 | x
    
    S5 := x S5 | T5
    T5 := y T5 z | S5 z | z
    
    S6 := x S6 | T6
    T6 := y T6 z | y S6 | y
    

    To finish the grammar off, just make the start symbol S for L's CFG produce each of the start symbols S3, S4, S5, S6:

    S := S3 | S4 | S5 | S6