Example #1
0
static void generateRandomSentences(const map<string, Definition>& grammar,
		int numSentencesNeeded) {
	for (int i = 0; i < numSentencesNeeded; ++i) {
		Definition defin = grammar.at("<start>");

		Production prod = defin.getRandomProduction();
		expendProduction(prod, grammar);
		cout << endl;
	}
}
static void expandOn(const map<string, Definition>& grammar, int aNonTerminalPos, vector<string>& aResult)
{
    if(aNonTerminalPos == -1)
    {
      // Base case //
      
      return;
    }
    else
    { 
      // Recursive case //

      auto iterator = grammar.find(aResult[aNonTerminalPos]);

      // If non-terminal is not defined then display error msg and exit.
      if(iterator == grammar.end()) {
        cout << "Could not find \"" << aResult[aNonTerminalPos] << "\" in the grammar file." << endl;
        exit (EXIT_FAILURE);  
      }

      Definition myDefinition = iterator->second;

      Production myRandProduction = myDefinition.getRandomProduction();
      
      // Get iterator 1 passed pos to insert.
      auto resultIterator = aResult.begin()+aNonTerminalPos+1;
      aResult.insert(resultIterator, myRandProduction.begin(), myRandProduction.end());
      
      // Get new valid iterator and delete expanded non-terminal.
      resultIterator = aResult.begin()+aNonTerminalPos;
      aResult.erase(resultIterator);

      // Iterate through result vector to expand on non-terminals.
      // Start from previously expanded position.
      int newNonTerminalPos = -1;
      int pos = aNonTerminalPos;
      for(auto start = aResult.begin()+aNonTerminalPos; start != aResult.end(); start++)
      {
        // Check if non-terminal.
        if( (*start)[0] == '<')
        {
          newNonTerminalPos = pos;
          break;
        }
        pos++;
      }
      
      // Recurse.      
      expandOn(grammar, newNonTerminalPos, aResult);
    }
}
Example #3
0
static void expendProduction(Production& production, const map<string, Definition>& grammar) {

	for (auto iter = production.begin(); iter < production.end(); ++iter) {
		string str = *iter;

		if (str.find('<') == std::string::npos) {
			cout << str << " ";
		} else {
			Definition def = grammar.at(str);
			Production prod = def.getRandomProduction();
			expendProduction(prod, grammar);
		}
	}
}