Write the shortest program you can in any language that reads from stdin a context-free grammar and the number of sentences to produce and generates that many random sentences from the grammar.
Input Specification
Input will come in from stdin in the following format:
n <START>
{"<A>":["as<A>df","0<A>","<B><C>","A<A>", ...], "<B>":["1<C>1","\<<T>>",...], ...}
n is the number of sentences to generate. <START> is identifier of the starting nonterminal symbol.
The grammar is enclosed in the {} and is formatted as follows:
- Rules are of the form
"<S>":[productions].<S>is the identifier of the nonterminal.- Rules are delimited with commas.
- The right-hand side of a rule is a double-quoted string whose first and last characters are "<" and ">", respectively. The remaining character should be in
[A-Z](upper-case alpha).
productionsis a comma-delimited list of double-quoted strings, representing productions. All characters, including whitespace, in the rule are terminal symbols, except those that are enclosed in angle brackets ("<"and">"), which are non-terminal symbols and will be the left-hand side of another rule. An open angle bracket may be escaped, but there is no need to escape a close angle bracket.- Productions will not contain newlines or the newline escape sequence.
Output Specification
You should print each generated sentence to stdout with a trailing newline.
UPDATE
Sample Input
5 sets of balanced parentheses:
5 <S>
{"<S>":["<S><S>", "(<S>)", ""]}
4 RPN (postfix) arithmetic expressions (note whitespace within strings is significant, whitespace elsewhere is not (the grammar spans multiple lines)):
4 <S>
{"<S>":["<N>", "<S> <S> <O>"], "<O>":["+","-","*","/"], "<N>":["<D><N>", "<D>"],
"<D>":["1","2","3","4","5","6","7","8","9","0"]}
Sample Output
First example (the empty string is in the language, so line 4 is intentionally blank):
(())()
()
()()()
(())(()())((((()))()()))
Second example:
1535235 76451 +
973812
312 734 99 3 + / *
1 1 1 1 1 + - * +
\<<T>>indicate? – Joey Adams Feb 11 '11 at 3:00\<<T>>would produce\<1>, which would produce a<1>as the final output. Yes, languages with JSON support would have a slight advantage, (though the escaped angle brackets should throw a wrench in that), but it at least levels the playing field for those languages not named "Perl". – Hoa Long Tam Feb 11 '11 at 3:13