Zduff Zduff - 1 month ago 9
C++ Question

What is an efficient method to force uniqueness using rand();

If I used (with appropriate #includes)

int main()
{
srand(time(0));
int arr[1000];
for(int i = 0; i < 1000; i++)
{
arr[i] = rand() % 100000;
}
return 0;
}


To generate random 5-digit ID numbers (disregard iomanip stuff here), would those ID numbers be guranteed by
rand()
to be unique? I've been running another loop to check all the values of the array vs the recently generated ID number but it takes forever to run, considering the nested 1000 iteration loops. By the way is there a simple way to do that check?

Answer

Since the question was tagged ,
you should consider using <random> in place of rand().

Using a standard distribution engine, you can't guarantee that you will get back unique values. If you use a std::set, you can keep retrying until you have the right amount. Depending on your distribution range, and the amount of unique values you are requesting, that may be adequate.

For example, here is a customized function to get n unique values from range [x,y].

#include <unordered_set>
#include <iostream>
#include <random>

template <typename T>
std::unordered_set<T> GetUniqueNumbers(int amount, T low, T high){

    static std::random_device random_device;
    static std::mt19937 engine{random_device()};
    std::uniform_int_distribution<T> dist(low, high);

    std::unordered_set<T> uniques;
    while (uniques.size() < amount){
      uniques.insert(dist(engine));
    }

    return uniques;
}

int main(){

  //get 10 unique numbers between [0,100]
  auto numbers = GetUniqueNumbers(10,0,100);
  for (auto number: numbers){
    std::cout << number << " ";
  }

}