Question

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

Verified
Answered 1 year ago
Answered 1 year ago
Step 1
1 of 5

In 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:

  1. Map<String, String[ ]> ruleMap: This is used to store a rule map with the rules being the key and rule expressions as value.

  2. 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

1/4

1/7