Write a program that takes a grammar G in Chomsky normal form and
a string
as
input, and tells whether or not w is in L(G).
The input grammar is presented in the format described in the first
programming assignment. There is an extra line specifying the string w,
as in the following example:
TERMINALS: a b
VARIABLES: S A B C
START: S
S -> AB
S -> BC
A -> BA
A -> a
B -> CC
B -> b
C -> AB
C -> a
STRING: abab
The following observation gives the key of the algorithm:
iff
there are two variables B and C
(not necesarily distinct) and a number k,
, such that:
An efficient way of organizing the computation is the following.
For each
, let
denote the set of variables
that can generate the string
, i.e.,
(Note that, since
,
w is generated by G if and only if
.) With this
notation, the sets
can be computed as follows: