Using Java, a program that reads as input an arbitrary context-free grammar from a text file and then derives/enumerates five strings from the grammar. The file cfg.txt can be used to test your...


Using Java, a program that reads as input an arbitrary context-free grammar from a text file and then derives/enumerates five strings from the grammar. The file cfg.txt can be used to test your program. The grammar represented in cfg.txt is the following grammar for non-palindromes (from input alphabet {a,b}):


S -> aSa | bSb | X
X -> aYb | bYa
Y -> aY | bY | lambda
This is formatted in cfg.txt as follows:


S aSa
S bSb
S X
X aYb
X bYa
Y aY
Y bY
Y *
An asterisk is used for lambda. Assume that the first state listed in the input file is the start state. Read the grammar into a map (aka hash or dictionary) where the key is a variable and the value is a list of right-hand sides. If you are using Java, you could use Hashtable by declaring a Hashtable of the following type:
Hashtable>
Do not write the program specific to this grammar in cfg.txt. Further, assume that the test file will have more than three variables, and productions on the right hand side can contain more than three terminals or variables. You should modify cfg.txt to ensure that it will works with a larger grammar. In general, the loop which reads in the grammar should look up the variable in the hash table. If the table returns null, it means that the variable is not present yet, so an array list should be created, the right hand side will be added to it, and stored into table. If the variable already exists, simply add the right hand side to the end of the array list (returned from the hash table).
After reading the grammar, simulate the derivation of a string in the language of a grammar by pushing the start variable onto a stack. In Java, the Stack would be of this type:


Stack
Next, follow this procedure:
while stack not empty:
pop a character
if it's a terminal, print it
otherwise push one of its right hand sides, chosen randomly
Generate five strings randomly for this grammar.




public class CFG {


public static void main(String[] args) throws Exception {
Hashtable> hash = new Hashtable<>();
File theFile = new File("cfg.txt");
Scanner keyboard = new Scanner(theFile);


while (keyboard.hasNext()) {
String left = keyboard.next();
String right = keyboard.next();
ArrayList prods = hash.get(left);


if (prods == null) {
prods = new ArrayList<>();
}
prods.add(right);
hash.put(left, prods);
}

Jun 04, 2022
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here