Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using namespace std;
- //Function Definition
- void initializeStructure(istream& input, HashMap<string, Vector<string>> &structure);
- string makeRandomString(string const &symbol, HashMap<string, Vector<string>> const &structure);
- string modifyResult(string &result, string &element, HashMap<string, Vector<string>> const &structure);
- /**
- * Generates grammar for a given symbol a certain number of times given
- * a BNF input file.
- *
- * This will be called by grammarmain.cpp.
- *
- * @param input - Input stream of BNF file.
- * @param symbol - Symbol to generate
- * @param times - Number of times grammar is generated
- * @return Vector of strings of size times with random generations of symbol
- */
- Vector<string> grammarGenerate(istream& input, string symbol, int times) {
- HashMap<string, Vector<string>> structure;
- initializeStructure(input, structure);
- Vector<string> randomStrings;
- for (int i = 0; i < times; i++) {
- string randomString = makeRandomString(symbol, structure);
- randomStrings.add(randomString);
- }
- return randomStrings; // This is only here so it will compile
- }
- void initializeStructure(istream& input, HashMap<string, Vector<string>> &structure) {
- while(!input.eof()) {
- string line;
- getline(input, line);
- string nonTerminal;
- nonTerminal = line.substr(0, line.find("::="));;
- if(structure.containsKey(nonTerminal) || nonTerminal == "") {
- throw("Exception!");
- }
- Vector<string> rules = stringSplit(line.substr(line.find("::=") + 3, line.size()), "|");
- structure.put(nonTerminal, rules);
- }
- }
- string makeRandomString(string const &symbol, HashMap<string, Vector<string>> const &structure) {
- string result;
- if (!structure.containsKey(symbol)) {
- return symbol;
- }
- Vector<string> rules = structure.get(symbol);
- int randomE = randomInteger(0, rules.size() - 1);
- string element = rules.get(randomE);
- if(stringContains(element, " ")) {
- Vector<string> eleSplit = stringSplit(element," ");
- for (int i = 0; i < (int) eleSplit.size(); i++) {
- result = modifyResult(result, eleSplit[i], structure);
- }
- } else {
- result = modifyResult(result, element, structure);
- }
- return result;
- }
- string modifyResult(string &result, string &element, HashMap<string, Vector<string>> const &structure) {
- if (structure.containsKey(element)) {
- result += makeRandomString(element, structure);
- } else {
- result += element + " ";
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement