+ 3

# How to generate random numbers without repetition or duplicates in C\C++

C\C++

7 Answers

- 3

Daramola Oluwafemi Michael
I learned this from youtube, u need to include ctime header
#include <ctime>
void randomGenerator()
{
srand(time(0));
for (int i=0; i<5; i++)
{
std::cout << 1+(rand()%100); }
}
U wont get same number sequence everytime u run the code

+ 7

If there are no repetitions or duplicates, I don't think that they can be truly called random numbers.

+ 4

Using the functions srand and rand from cstdlib, you create random numbers and put them into an array, but for every number you check, if it's already contained in the array, and if yes, you repeat the procedure.
If it's okay that the random numbers are all in a range, you could also just create a range of numbers from, say, 1 to 100 and shuffle the array afterwards.

+ 2

There are certain simple 'sorting' algorithms for this.
For example google Fisher-Yates shuffle, that's quick and easy to do.

+ 2

Here a proposition, which might not be really efficient:
- Ensure that the number of random number desired in smaller than the maximum number possible. e.g. 7 different values on a 6 sided dice would not be ok.
- Use a std::unordered_set to insert each generated number until its size is the desired value
- Copy each value in a std::vector
- You might then want to use the shuffle function to guarantee a random order, although just copying from the unordered_set is more than enough.
Voilà! You now have a list of Unique (guaranteed) and Random value in a random order in a contiguous memory.
If having the values in contiguous memory not important, don't copy to a vector.

+ 1

How do I shuffle

+ 1

If you a looking for true randomness, use random.org's API.