Regarding the shuffle, I don't think that is the direction I am supposed to go in. I am supposed to generate a new random number every time i fill the array |
Think of this (case worse than yours):
1. The valid values are 1..1'000'000
2. You need 1'000'000 unique random numbers
Following your "supposed" algorithm, the beginning of the array will seem easy. However, to get the last "random" number, you would have to repeat the
1 + rand() % 1'000'000
until you do get the one and only missing unique value. It can take more than 1'000'000 tries.
The shuffling calls rand() exactly N-1 times. 999'999 calls for the million case to get
all random numbers and not a single repeat required.
Your valid values seem to be 0..14 (
+ 1 + col*15
).
You need only 5 values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include <utility> // std::swap
#include <cstdlib>
#include <ctime>
int main() {
const int N = 15;
int pool[N];
srand( time(0) );
for ( int col = 0; col < 4; ++col ) {
// reset pool
for ( int ind=0; ind < N; ++ind ) {
pool[ ind ] = ind;
}
// shuffle
for ( int i= N-1; i>0; --i ) {
int r = rand() % (i+1);
std::swap( pool[ i ], pool[ r ] );
}
// show
std::cout << "L=" << col << ": ";
for ( int num=0; num < 5; ++num ) {
std::cout << ' ' << pool[ num ] + N * col + 1;
}
std::cout << '\n';
}
return 0;
}
|
L=0: 8 10 7 13 4
L=1: 23 22 16 18 30
L=2: 39 41 42 35 36
L=3: 48 56 59 47 58 |
Are they "random", are they unique?