Like Tree2Likes
  • 2 Post By laserlight

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

This is a discussion on Generate random Number without repetition.... Need advice and some help.. within the C Programming forums, part of the General Programming Boards category; Hi, I am writing a program to generate 6 random numbers from 1 to 40 inclusive. So far, I have ...

  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
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    993
    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
    200
    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
    22,306
    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 01:41 PM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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
    22,306
    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.
    thedm007 and pprav05 like this.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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
    22,306
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    993
    [...] 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, 09:57 AM
  3. generate a random number
    By waxydock in forum C++ Programming
    Replies: 5
    Last Post: 06-05-2005, 08:43 PM
  4. Replies: 11
    Last Post: 07-16-2002, 12:39 PM
  5. Ask about generate Random number
    By ooosawaddee3 in forum C Programming
    Replies: 2
    Last Post: 07-01-2002, 05:30 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21