I've seen the approaches for creating a vector of unrepeated random numbers based on std::random_shuffle
, however I need to implement an alternative approach. This is my code:
std::vector<int> create_unrepeated_random(int v_size, int v_max) {
// Max index value must be grater than the number of vector size
assert(v_max > v_size);
std::vector<int> ret;
int val = 0;
for (int i = 0; i < v_size; i++) {
val = std::rand() % v_max;
// Keep generating new values until we generate one that is not already in
// output vector
if (ret.size() > 0) {
while (!std::binary_search(ret.begin(), ret.end(), val)) {
val = std::rand() % v_max;
}
}
ret.push_back(val);
}
assert ((int)ret.size() == v_size);
for (auto &v: ret) printf("%d ", v);printf("\n");
return ret;
}
However, this is not working, don't know why. Some numbers appear repated sometimes.
BUT if I change the while
loop to
while (std::binary_search(ret.begin(), ret.end(), val))
this creates a vector of repeated random numbers. What is wrong here?