CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11

Threaded View

  1. #2
    Join Date
    May 2000
    Location
    Washington DC, USA
    Posts
    715
    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.
    Last edited by JMS; February 9th, 2004 at 12:18 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured