I am trying to create something that generates a random array with no duplicate values. I've already looked at other answers but none seem to help me understand. I cannot think of a way to actually generate random numbers that contain no duplicates. Here is what i have tried so far:
srand(time(NULL));
int numbers [4];
for (int x=0; x!=4;x++)
{
numbers[x] = 1 + (rand() % 4) ;
printf("%d ", numbers[x]);
}
Any help will be appreciated.
After you generate each random number, loop through the previous values and compare. If there's a match, re-generate a new value and try again.
How about this:
Of course, the bigger
NUMS
is, the longer it will take to execute thewhile
loop.You can use your own random number generator which has the sequence greater or equal to length of the array. Refer to http://en.wikipedia.org/wiki/Linear_congruential_generator#Period_length for instructions.
So you need LCG with expression Xn+1 = (aXn + c) mod m. Value m must be at least as large as length of the array. Check "if and only if" conditions for maximum sequence length and make sure that your numbers satisfy them.
As a result, you will be able to generate random numbers with satisfactory randomness for most uses, which is guaranteed to not repeat any number in the first m calls.
In c++, all you need is:
http://www.cplusplus.com/reference/algorithm/random_shuffle/
Update: OK, I had been thinking that a suitable map function could go from each index to a random number, but thinking again I realize that may be hard. The following should work:
You start off filling a container with consecutive elements beginning at
0
std::iota(begin(vec), end(vec), 0);
then you get yourself a decent random number generator and seed it properly
std::mt19937 rng(std::random_device{}());
finally you shuffle the elements using the rng
std::shuffle(begin(vec), end(vec), rng);
live on coliru
On some implementations
random_device
doesn’t work properly (most notably gcc on windows) and you have to use an alternative seed, i.e. the current time →chrono
.It's just a way. it should work, of course there are better ways