I've been working endlessly on this project. I'm suppose to write the following method, but I'm not sure how to approach it. The following are the methods that I'm stuck on.
public String generate(String symbol){}: Use the grammar in the rules map to randomly generate an occurrence of the given symbol. Throw an IllegalArgumentException if the grammar does not contain the given nonterminal symbol. Call a private recursive helper method appropriately.
public String[] generate(String symbol, int times){} : This method does the same thing as the preceding method, except that it retus multiple (times) randomly generated occurrences of the given symbol in a String array. It should throw an IllegalArgumentException under the same circumstances as above, and if times is less than 0. Call a private recursive helper method appropriately.
This is what I've worked on so far.
import java.util.*;
import java.io.*;
public class GrammarProcessor {
private Map<String, String[]> rules = new TreeMap<>();
private static final Random d = new Random();
/* Constructor */
public GrammarProcessor(List<String> grammar) {
for (String element : grammar) {
if (grammar.contains("::=")) {
String[] split1 = element.split("::="); // splits to key and value
String part1 = split1[0].trim();
String part2 = split1[1].trim();
if (grammar.isEmpty() || rules.containsKey(part1)) {
throw new IllegalArgumentException(); // breaks when key is already in rules
}
String[] split2 = part2.split("[|]");
rules.put(part1, split2);
}
}
} // End of GrammarProcessor()
/* Method retus TRUE if the condition inside the if statement if symbol is equal
to any of the specified strings, otherwise retu FALSE */
public boolean grammarContains(String symbol) { // nonterminal symbols
retu rules.containsKey(symbol); // retu TRUE if symbol is in rules else FALSE
} // End of grammarContains() - Done
/* Method retus nonterminal symbol */
public String getSymbols() {
retu rules.keySet().toString();
} // End of getSymbols()
/* Helper Method */
private String generate(String symbol, int n, String generated) {
if (grammarContains(symbol) == false) {
symbol += " ";
}
while (symbol.equals("<s>") || symbol.equals("<np>") ||
symbol.equals("<pn>") || symbol.equals("<adjp") ||
symbol.equals("<dp>") || symbol.equals("<n") ||
symbol.equals("<vp>") || symbol.equals("<tv>") ||
symbol.equals("<iv>") || symbol.equals("E") ||
symbol.equals("T") || symbol.equals("OP") ||
symbol.equals("F1") || symbol.equals("F2")) {
String[] arr = rules.get(symbol);
for (String element : arr[d.nextInt(arr.length)].trim().split("[ t]+")) {
if (n != 0) {
generated += element + " ";
retu generate(symbol, n-1, generated);
} else {
break;
}
}
}
retu generated;
}
public String generate(String symbol) {
if (grammarContains(symbol) == false) throw new IllegalArgumentException();
} // End of generate()
} // End of GrammarProcessor
