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?
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.
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* = newunsigned[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.