+ 3

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


31st Dec 2019, 2:26 PM
Daramola Oluwafemi Michael
Daramola Oluwafemi Michael - avatar
6 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
31st Dec 2019, 5:06 PM
‎צחק‎اسحاق - avatar
+ 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.
31st Dec 2019, 3:18 PM
HonFu - avatar
+ 2
There are certain simple 'sorting' algorithms for this. For example google Fisher-Yates shuffle, that's quick and easy to do.
31st Dec 2019, 4:22 PM
HonFu - avatar
+ 1
How do I shuffle
31st Dec 2019, 3:53 PM
Daramola Oluwafemi Michael
Daramola Oluwafemi Michael - avatar
+ 1
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.
2nd Jan 2020, 4:21 AM
Jean-Philip Sabourin
Jean-Philip Sabourin - avatar
+ 1
If you a looking for true randomness, use random.org's API.
2nd Jan 2020, 12:42 PM
ReimarPB - avatar