generate a random number, then exclude that number from being generated again?

So, I have a typical system time-seeded number generator and I need it to exclude the number it generates from generated again in the same run (it's a simple Q&A program essentially, where the number generated corresponds to the array index of the question asked. Without this, I run into the problem of the same question being asked multiple times in the same run). Any help?

1
2
3
int secret;
srand((unsigned)time(0));
secret = rand() % 6;	    
Typical approach is to shuffle the array, or if it's expensive, to shuffle a container that holds all possible indexes:

modern C++:
1
2
3
std::vector<int> v(10);
std::iota(v.begin(), v.end(), 1); 
std::random_shuffle(v.begin(), v.end()); 

demo: http://ideone.com/kw0QJ

old C++:
1
2
3
std::vector<int> v(10,1 ); // 1, 1, 1, ...
std::partial_sum(v.begin(), v.end(), v.begin()); // 1, 2, 3, ... or use a loop
std::random_shuffle(v.begin(), v.end()); 

demo: http://ideone.com/lgHQv

now the ten values stored in the vector are ten random integers 0...9, with no repetitions
Last edited on
Topic archived. No new replies allowed.