Yet another method...
The STL and C++11 are terrific, but what happens if no canned solution method seems evident?
Write your own???
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 29 30 31 32 33 34 35 36
|
int main()
{
const int sizeA = 25;
int A[sizeA];// contains the set of unique values
int i=0;
for(i=0; i<sizeA; ++i)
A[i] = i + 1;//1 2 3 4...
const int sizeB = 10;
int B[sizeB];// result storage
// When a value is selected, remove it from the pool of values being selected from
// swap sizeB randomly selected elements from "left end" of A to the "right end" of A
// left/right split is at A[idxSplit]
int idxSplit = sizeA - 1;
for( i=0; i<sizeB; ++i )
{
int idxRand = rand()%( 1 + idxSplit );// random index into "left portion" of A
int temp = A[idxRand];// swap values
A[idxRand] = A[idxSplit];
A[idxSplit] = temp;
--idxSplit;
// catch the unique value just swapped (or copy from A[idxSplit+1] to A[sizeA-1] later)
B[i] = temp;
}
// show the B array
cout << "B: ";
for( i=0; i<sizeB; ++i )
cout << B[i] << " ";
cout << endl;
return 0;
}
|
Output:
B: 17 12 10 13 18 5 3 1 21 25
|
Actually, this method is more generally useful than this case suggests.
Sometimes the problem is to use a subset of specific values. Example:
A[] = { 1, 2, 3, 5, 7, 11, 13,... } could be used to support filling B with randomly selected unique prime numbers.
EDIT: If you are using all values in A, but you need them randomly shuffled then replacing line 17:
for( i=0; i<sizeB; ++i )
with
for( i=0; i<(sizeA-1); ++i )
would accomplish that on A itself (ie, no need for B).
A: 22 9 19 14 23 16 20 11 8 2 7 4 24 15 6 25 21 1 3 5 18 13 10 12 17 |
Of course, calling random_shuffle (from STL) on A[] would work fine too (sigh).
I guess that makes this my solution:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
template<class T>
void myRandomShuffle( T A[], unsigned size )
{
int idxSplit = size - 1;
while( idxSplit > 0 )
{
int idxRand = rand()%( 1 + idxSplit );
T temp = A[idxRand];// swap values
A[idxRand] = A[idxSplit];
A[idxSplit] = temp;
--idxSplit;
}
}
|