0
How to generate 256 random numbers without repeat?
I need to generate 256 random numbers in range 0-255 without repeating. I came up with many options and the numbers are constantly repeated. I usually compare in cycles. If the generated number matches the one already existing in the array, I again generate a new value in the same array element. And so on until you get 256 unique numbers. int newNums[256]; for(int i=0;i<256;i++){ newNums[i] = -1; } for(int el = 0; el<256;el++){ newNums[el] = rand() % 255; //earlier i use srand(time(0)) for(int pos=0, matches = 0; pos<=el; pos++){ if(newNums[el] == newNums[pos]){ matches++; if(matches > 1){ el--; break; } } } }
3 Réponses
+ 7
Doing it this way is very slow, because as the array fills up, you will get lots of duplicate numbers and waste a lot of loop cycles.
A better approach would be to fill the array with the numbers and just shuffle it randomly afterwards. Here is an example making full use of STL features:
https://code.sololearn.com/cO7vK5K9S5ya/?ref=app
The sample() algorithm is actually very easy to implement, and you could do it yourself using rand() if you wish. As a reference, here is how the STL implements it:
https://en.cppreference.com/w/cpp/algorithm/random_shuffle
If the library implementation feels not understandable, feel free to ask again.
+ 5
Влад Цислевский , what about the code you presented? Is it creating an error. Please give a clear description. Thanks!
+ 3
Влад Цислевский Unfortunately, my messenger is not working correctly. Regarding your DM:
std::iota is just a convenience function to fill the array. You might have to include <numeric> where it is actually defined:
https://en.cppreference.com/w/cpp/algorithm/iota
A simple for loop would do the job too.