Search code examples
context-free-grammar

Count words in context free grammar


So I have one issue with context free grammar that I didn't manage to solve. It's not for grade or something, so don't worry.

Problem goes like this:

There's a context free grammar that looks like

S -> S1 | S2

S1 -> aS1B | B

S2 -> S2aB | B

B -> bS | b

Task is to write a function (in any programming language) count_words(n). Function needs to return number of words with "n" length, that are "involved" in this context free language.

* let's say I call function with count_words(3), function must return number of possible words (inside that context free language) that are length of 3. That would be: bab, abb, aab etc.

Can anyone help me with that? I have no idea at all...suppose it's not hard but I can't force myself to think the right way.


Solution

  • You will need to simulate the grammar. Given the terminals a and b, construct an automaton that accepts your language. Since the grammar you present is a left-recursive grammar an option would be to construct a push-down automaton similar to an LR parser. After each symbol push if the resulting parse stack can be reduced to the starting symbol the string can be accepted by the grammar. Continue this until the desired string length.

    Essentially you're simulating the automaton and branching out since you'll try to simulate using all possible inputs after reducing the parse stack.

    You can possibly avoid to construct the automaton entirely and just look at which possible rules you are in given each state.