André Foote André Foote - 1 year ago 74
C++ Question

Trying to produce a unique sequence of random numbers per iteration

As the title states, I'm trying to create a unique sequence of random numbers every time I run this little program.

However, sometimes I get results like:


The code

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main() {
for (int i = 0; i < 3; i++) {
srand (time(NULL)+i);
cout << rand() % 3;
cout << rand() % 3;
cout << rand() % 3 << '\n' << endl;

Clearly srand doesn't have quite the magical functionality I wanted it to. I'm hoping that there's a logical hack around this though?

Edit1: To clarify, this is just a simple test program for what will be implemented on a larger scale. So instead of 3 iterations of rand%3, I might run 1000, or more of rand%50.
If I see 102 at some point in its operation, I'd want it so that I never see 102 again.

pjs pjs
Answer Source

Generate an array containing the 1000 three digit numbers. Shuffle it. Iterate through the shuffled array as needed, values will be unique until you've exhausted them all.

As other people have pointed out, don't keep reseeding your random number generator. Also, rand is a terrible generator, you should use one of the better choices available in C++'s standard libraries.