Generating Random Numbers Without Repeats - Part Two

VernonDozier 0 Tallied Votes 743 Views Share

I received some feedback on my earlier code snippet regarding how to generate unique random numbers and someone suggested I make a shorter, easier example, so here it is. This example simply generates the integers from 0 to 9 in random order without any repeats. It is basically the function GenerateRandomIntegers2 from my earlier snippet.

/* I received some feedback on my earlier code snippet regarding generating
   unique random numbers and someone suggested I make a shorter, easier
   example, so here it is.  This example simply generates the integers from
   0 to 9 in random order without any repeats.  It is basically the function
   GenerateRandomIntegers2 from my earlier snippet.
   
   srand, rand, and time appear to be part of the iostream library, but I have
   included ctime and cstdlib because you need them for the srand, time, and rand
   functions if you are not including iostream.
*/

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;


int main ()
{
    srand (time (NULL));
    bool picked[10];
    for (int i = 0; i < 10; i++)
         picked[i] = false;
    
    int array[10];  
    int value;
     
    for (int i = 0; i < 10; i++)
    {
        value = rand () % 10;
        if (picked[value])
            i--;  // already picked.  for-loop increments, so decrement here
        else
        {
            array[i] = value;
            picked[value] = true; // hasn't been picked yet.  Assign to array,
                                  // flag as picked.
        }
     }
     
     // display
     for (int i = 0; i < 10; i++)
         cout << array[i] << endl;   
    
     return 0;
}