Thread: Generate random Number without repetition.... Need advice and some help..

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    10

    Generate random Number without repetition.... Need advice and some help..

    Hi, I am writing a program to generate 6 random numbers from 1 to 40 inclusive.

    So far, I have been using the code below..

    However, the only problem is that from time to time, I'm getting repeating numbers.

    Is there any way to solve this issue???

    Here's the code:

    Code:
    # define M 6
    
    int main()
    {
        int j;
        int m_num[j];
        time_t seconds;
        
        int lower=1;
        int upper=40;
        
        time(&seconds);
        
        srand((unsigned int)seconds);
        
        for(j=0; j<M; j++)
        { 
            m_num[j]=rand()%(upper-lower+1)+1;   
        }
        
        printf("Generated numbers are:");
        
        for(j=0; j<M; j++)
        {
           printf(" \n %d \n", m_num[j]);
        }
        
        system("PAUSE");
        return 0;
    }


    note: i'm using Dev c++, and also Visual Studio sometimes..

  2. #2
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    Code:
    int j;
    int m_num[j];
    This is problematic, because j has no known value at the time you use it to initialize m_num. Perhaps you meant M?

    The easiest way to achieve what you want is probably to create an array with the values 1–40, shuffle that array, then pick off the first six values. Search for Fisher-Yates to see how to effectively shuffle an array.

  3. #3
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Even Dev-C++ should return a warning about using an uninitialized variable. For all we know, j could be a negative number randomly pulled out of memory. The reason that you will get repeating numbers is because random number generation is not truly random. Using the Fisher-Yates algorithm mentioned above would help you achieve a more random effect. Fisher-Yates Shuffle Alg.
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Rodaxoleaux
    The reason that you will get repeating numbers is because random number generation is not truly random.
    Not really: a "truly" random number generator would also be expected to produce repeating numbers, from time to time. It is merely a matter of "selecting at random with replacement" versus "selecting at random without replacement". The shuffle algorithm you suggested basically repeatedly selects at random without replacement, until an element has been selected for each position in the array.
    Last edited by laserlight; 11-01-2011 at 12:41 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    10
    Ok, I somehow managed to get another method to work..

    But when generating the random numbers... 0 also is being output... and I don't want this! I just want 1-40 inclusive..

    Below is the code: Any help is greatly appreciated

    Code:
    # define N 40
    
    
    int main() {
        int ran_num[N];   
        
        srand(time(0));  
         
        for (int i=0; i<40; i++) 
        {
            ran_num[i] = i;  
        }
        
        
            for (int i=0; i<(40-1); i++) 
            
            {
                int r = i + (rand() % (40-i)); 
                int temp = ran_num[i]; 
                ran_num[i] = ran_num[r]; 
                ran_num[r] = temp;
            }
            
            for (int c=0; c<6; c++) 
            {
                printf(" %d ", ran_num[c]);  
            }
            
            printf("\n");
       
       system("PAUSE");
       return 0;
    }

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by pprav05
    Ok, I somehow managed to get another method to work..
    It looks like it is the same method: shuffle the array.

    Quote Originally Posted by pprav05
    0 also is being output... and I don't want this! I just want 1-40 inclusive..
    Given the range [0, 39], add 1 to get [1, 40]. In your case, it means starting the initial values of the array at 1, not 0.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Nov 2011
    Posts
    10
    Many thanks.. It solved the problem..

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Why would you shuffle the array, when you could simply scan it?

    Code:
    int array[40];
    int i = 0;
    int j;
    
    while( i < 40 )
      { array[i] = (rand() % 40) + 1;
         for (j = 0; j < i; j++)
           if (array[j] == array[i])
             break;
         if ( ! (j < i) )
           i++; }

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by CommonTater
    Why would you shuffle the array, when you could simply scan it?
    Yeah, since the number of numbers that you are selecting at random without replacement is small compared to the range of numbers, rejecting repetition is a good solution. When the number of numbers you are selecting at random without replacement is large compared to the range of numbers, shuffling tends to be a better solution than rejecting repetition. Note that using rejection saves space: you only need an array of 6 ints, not 40 ints.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Sep 2007
    Posts
    1,012
    [...] rejecting repetition is a good solution.
    The reason I suggested shuffling an array is that rejecting repetition has the possibility of infinitely looping. If the PRNG gets in a loop of generating numbers, none of which satisfies the necessary condition, then you've got a problem.

    Of course, this is rather unlikely, but PRNGs have historically been one of the weak areas of implementation so I'd err on the side of caution. This is also one of those problems that might always work on one system no matter how much you stress test it, but could fail elsewhere.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to generate a random number in c?
    By blogchama in forum C Programming
    Replies: 2
    Last Post: 01-20-2011, 10:39 AM
  2. Generate Random Number
    By peacealida in forum C++ Programming
    Replies: 10
    Last Post: 04-06-2008, 08:57 AM
  3. generate a random number
    By waxydock in forum C++ Programming
    Replies: 5
    Last Post: 06-05-2005, 07:43 PM
  4. Replies: 11
    Last Post: 07-16-2002, 11:39 AM
  5. Ask about generate Random number
    By ooosawaddee3 in forum C Programming
    Replies: 2
    Last Post: 07-01-2002, 04:30 AM

Tags for this Thread