Search code examples
grammarcontext-free-grammar

Context free grammar for {a*b*c*} - {a^n b^n c^n | n >=0}


I'm having trouble with this problem. I believe its telling me that no string can be generated that has even # of a's b's and c's. This is due to the subtraction of the second set.

A good string from a newly formed CFG should be something like aaabbc or abbbcc and so on.

So I tried breaking the problem into three parts...

  1. Single states

    a.) S(1) -> aS(1) | a | ^
    b.) S(2) -> bS(2) | b | ^
    c.) S(3) -> cS(2) | b | ^
    
  2. Two States

    a.) S(4) -> aS(4)b | S(1) | S(2)
    b.) S(5) -> bS(5)c | S(2)
    c.) S(6) -> aS(6)c | S(3) | S(1)
    
  3. States w/AB states

    a.) S(7) -> S(1) | S(4)S(6)
    b.) S(8) -> S(2) | S(5)S(6)
    c.) S(9) -> S(3) | S(6)S(3)
    

    with an orginal start state of ...

    S ->  S(7) | S(8) | S(9)
    

However I'm having problems building strings like aaaabbbcc ...

Am I forming CFGs incorrectly? I felt like I was on the right track but now I'm quite lost.


Solution

  • So I split the problem into 2 sub problems

    The number of a's is different from the number of b's. Therefore the a's and c's or b's and c's can be the same.

    The number of b's is different from the number of c's. Therefore the a's and b's or a's and c's can be the same.

    Edit: More formally as stated by Rici {anbmc* | nm } ∪ {a*bncm | nm }

    //a and b is different
    S-->XR
    //b and c is different
    S-->DY
    
    //Genarates a string where a is more than b
    X--> aXb | A
    A --> aA  | a
    
    //Genarates a string where b is more than a
    X--> bXa | B
    B --> bB  | b
    
    //Genarates a string where b is more than c
    Y--> bYc | B
    B --> bB  | b
    
    //Genarates a string where c is more than b
    Y--> cYb | C
    C --> cC  | c
    
    R-->Rc|c|^
    D-->Da|a|^