I have an assignment to make a program in C that displays a number (n < 50) of valid, context-free grammar strings using the following context-free grammar:
S -> AA|0
A -> SS|1
I had few concepts of how to do it, but after analyzing them more and more, none of them were right.
For now, I'm planning to make an array and randomly change [..., A, ...]
for [..., S, S, ...]
or [..., 1, ...]
until there are only 0s and 1s and then check whether the same thing was already randomly generated.
I'm still not convinced if that is the right approach, and I still don't know exactly how to do that or where to keep the final words because the basic form will be an array of chars of different length. Also, in C, is a two dimensional array of chars equal to an array of strings?
Does this make any sense, and is it a proper way to do it? Or am I missing something?
[A, S, S, 0, A, 1]
also a valid outcome? Because then you could just do a random number of steps. I'm not sure an array is the best structure, as steps may increase the length of the string. Does it have to be C, or is C++ allowed as well? If you are looking for solutions with only terminals, it may be worth proving what they look like first (e.g. you only get even numbers of consective0
s and1
s, or an1
can only occur between two0
s, etc) and use those rules to generate a result. – CompuChipprintf
calls that print manually computed strings that conform to the grammar. – Kaz