This is not the most efficient code and but if the nouns you're working with get's bigger and bigger it gets better. An alternative would keep track of the random number and then if the strstr found a match you could then loop on the random number generator until you found a different one...
Anyway.. this works but will probable make you wait a couple of nano secons longer for your result....
Code:srand(time(NULL)); // Seed rand() char sentence[maxSentence+1] = "";// Initialize sentence to null string. //sentence output in the format "The <noun><verb> the <noun>." for (int k = 0; k < numSentences; k++) { strcat(sentence,upperThe); // The strcat(sentence,space); // (space) strcat(sentence, noun[(rand()%numWords)]->getNoun()); // random noun strcat(sentence,space); // (space) strcat(sentence, verb[(rand()%numWords)]->getVerb()); // random verb strcat(sentence,space); // (space) strcat(sentence,lowerThe); // the strcat(sentence,space); // (space) // New Code int iRandom = (rand()%numWords); for( ; ; ) // infinite loop; while(TRUE) will work too { if(!strstr( sentence, noun[iRandom]->getNoun()) { // new noun is not part of the sentence strcat(sentence, noun[iRandom]->getNoun()); // we added our sencond noun so break out of the infinite loop break; } else { // new noun already in the sentence so pick another one iRandom = (rand()%numWords); } } // end New Code strcat(sentence,period); // (period) cout << sentence << endl; // sentence[0] = '\0'; // Reset sentence to null string for next // better to zap it all the way memset( sentence, '\0', sizeof(sentence)); // resets the entire string rather than the first character iteration.




Reply With Quote