Random Number Generator

I have this random number generator code here that prints out 30 random numbers in a range of 0 - 60. But what I want to do is print out the numbers so that the same number is not used more then once? What kind of algorithm can you use for this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{

srand(time(NULL));
for(int i=1; i<31; i++)
{
cout<<rand() % 60 <<" ";
if(i % 10 == 0)
cout<<endl;
}


system("pause");
return 0;
}
I am just learning C++, but I will give my $0.02 anyway.

I think you should create a vector of size 30, and use push_back() to add each random number to that vector. After the random number is generated, cycle it through the vector elements to see if it matches any existing numbers in that vector. If not, let the program continue to push_back. If so, stop the loop and generate another random number.

Sorry that I can't put it into code.
Unfortunately, I'm just learning too and haven't come across vector or push_back() yet.

The only thing I can think of would be to do some kind of while loop that would keep on generating a new number if a number has allready been used?

Something like this?
while(number from draw == number from previous draw)
{
draw another random number
}
You could create a vector (or array) with 61 elements containing the numbers 0 to 60. Then do a std::random_shuffle() on the vector/array from the #include <algorithm> header. After that just select the first 30.
I would personally go for something along these lines (untested!):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
unsigned RandomArray* = new unsigned[30];
for( int i = 0; i < 29; i++ ) // 29, since 0 is a piece of the array, too. So it still counts up to 30.
{
      Label:
      srand(ctime(0));
      RandomArray[i] = rand() % 61; // More elegant solutions are available, using RAND_MAX
      if (i) // if i is non-zero
      {
            for( int j = 0; j < i ; j++ )
            {
                  if (RandomArray[i] == RandomArray[j]) goto Label;
            }
      }      
}

Either or both of the <'s might have to be changed to <=... or not. I'm never really good with those. Hope you get the idea.

EDIT:
I just re-read Galik's approach, and I'd personally go for his.
Last edited on
Topic archived. No new replies allowed.