Related questions with answers
Write a recursive program to generate random sentences from a given BNF grammar. A BNF grammar is a recursively defined file that defines rules for creating sentences from tokens of text. Rules can be recursively self-similar. The following grammar can generate sentences such as “Fred honored the green wonderful child”:
<s>::=<np> <vp>
<np>::=<dp> <adjp> <n>|<pn>
<dp>::=the|a
<adjp>::=<adj>|<adj> <adjp>
<adj>::=big|fat|green|wonderful|faulty|subliminal|pretent
ious
<n>::=dog|cat|man|university|father|mother|child|televisi
on
<pn>::=John|Jane|Sally|Spot|Fred|Elmo
<vp>::=<tv> <np>|<iv>
<tv>::=hit|honored|kissed|helped
<iv>::=died|collapsed|laughed|wept
Solution
VerifiedIn this project, we want to generate random sentences using the given BNF grammar.
We will create a BNFGrammar class that will solve this problem using recursion. This class will have two attributes:
-
Map<String, String[ ]> ruleMap: This is used to store a rule map with the rules being the key and rule expressions as value.
-
List<String> rulesList: This is used to store the rules.
We will also have a main method that will be used to run the program.
Create an account to view solutions
Create an account to view solutions
More related questions
- differential equations
- linear algebra
- computer science
1/4
- differential equations
- linear algebra
- computer science
1/7