Advertisement
Guest User

Untitled

a guest
Apr 27th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. using namespace std;
  2.  
  3. //Function Definition
  4. void initializeStructure(istream& input, HashMap<string, Vector<string>> &structure);
  5. string makeRandomString(string const &symbol, HashMap<string, Vector<string>> const &structure);
  6. string modifyResult(string &result, string &element, HashMap<string, Vector<string>> const &structure);
  7.  
  8.  
  9. /**
  10. * Generates grammar for a given symbol a certain number of times given
  11. * a BNF input file.
  12. *
  13. * This will be called by grammarmain.cpp.
  14. *
  15. * @param input - Input stream of BNF file.
  16. * @param symbol - Symbol to generate
  17. * @param times - Number of times grammar is generated
  18. * @return Vector of strings of size times with random generations of symbol
  19. */
  20.  
  21. Vector<string> grammarGenerate(istream& input, string symbol, int times) {
  22. HashMap<string, Vector<string>> structure;
  23. initializeStructure(input, structure);
  24. Vector<string> randomStrings;
  25. for (int i = 0; i < times; i++) {
  26. string randomString = makeRandomString(symbol, structure);
  27. randomStrings.add(randomString);
  28. }
  29. return randomStrings; // This is only here so it will compile
  30. }
  31.  
  32. void initializeStructure(istream& input, HashMap<string, Vector<string>> &structure) {
  33. while(!input.eof()) {
  34. string line;
  35. getline(input, line);
  36. string nonTerminal;
  37. nonTerminal = line.substr(0, line.find("::="));;
  38. if(structure.containsKey(nonTerminal) || nonTerminal == "") {
  39. throw("Exception!");
  40. }
  41. Vector<string> rules = stringSplit(line.substr(line.find("::=") + 3, line.size()), "|");
  42. structure.put(nonTerminal, rules);
  43. }
  44. }
  45.  
  46. string makeRandomString(string const &symbol, HashMap<string, Vector<string>> const &structure) {
  47. string result;
  48. if (!structure.containsKey(symbol)) {
  49. return symbol;
  50. }
  51. Vector<string> rules = structure.get(symbol);
  52. int randomE = randomInteger(0, rules.size() - 1);
  53. string element = rules.get(randomE);
  54.  
  55. if(stringContains(element, " ")) {
  56. Vector<string> eleSplit = stringSplit(element," ");
  57. for (int i = 0; i < (int) eleSplit.size(); i++) {
  58. result = modifyResult(result, eleSplit[i], structure);
  59. }
  60. } else {
  61. result = modifyResult(result, element, structure);
  62. }
  63. return result;
  64. }
  65.  
  66. string modifyResult(string &result, string &element, HashMap<string, Vector<string>> const &structure) {
  67. if (structure.containsKey(element)) {
  68. result += makeRandomString(element, structure);
  69. } else {
  70. result += element + " ";
  71. }
  72. return result;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement