I want to fill a vector with random integers but there can't be duplicates in it.
First off, I have this code to put numberOfSlots random integers between 0 and 7 in the vector (numberOfSlots can be 2 to 20):
srand((unsigned int)time(NULL));
unsigned int min = 0;
unsigned int max = 7;
std::vector<unsigned int> v;
for (int i = 0; i < numberOfSlots; i++) {
unsigned int rdm = std::rand() % (max - min + 1) + min;
v.push_back(rdm);
}
This is the code for when duplicate integers are allowed. This is working fine!
Now I want to the change that code so that from the same random pool of possible integers (min to max) the generated random integer is only added if it's not already in the vector.
So if for example numberOfSlots is 5, then the vector will have 5 entries that were randomly chosen from the pool but are not the same, e.g. 7, 1, 3, 5, 0. If numberOfSlots is 8, the vector will be for example 3, 1, 2, 7, 6, 0, 4, 5.
I know how to shuffle the vector and stuff but I am not able to get this working. I think I have to use a while loop and check all already existing integers in the vector against the new random to be added number and if it's already in there generate a new random number and check again, etc. but I don't know
I am a beginner and this is really hard. Can someone maybe give me a hint? I would appreciate it... thank you so much
You can populate your vector with values 0..N-1 (or your pool values), and thereafter shuffle it. See example:
// Initialize
for(i = 0; i < N; i++)
arr[i] = i;
// shuffle
for(i = N - 1; i > 0; i--) {
j = rand() % i;
swap(arr[i], arr[j]);
}