Solution
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int rand_select_elems(int a[], int len)
{
srand((unsigned)time(NULL));
static int l = 0;
int n = rand() % (len - l);
int m = l + n;
int t = a[l];
a[l] = a[m];
a[m] = t;
t = a[l];
l ++;
l %= len;
return t;
}
int main(int argc, char* argv[])
{
int a[20];
for(int i = 0; i < 20; i++){
a[i] = i;
}
for(int i = 0; i < 50; i ++){
cout.width(2);
cout << i << " ";
}
for(int i = 0; i < 50; i ++){
cout.width(2);
cout << rand_select_elems(a, 20) << " ";
}
cout << endl;
return 0;
}
Output
0 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 37 38 39 40 41 42 43 44 45 46 47 48 49
13 8 0 14 17 2 11 7 5 19 1 10 4 18 9 6 12 3 16 15 18 5 13 9 3 0 10 7 2 15 8 1 17 16 19 11 4 14 12 6 16 2 18 19 14 13 1 7 0 6
Problem
Write a method to randomly generate a set of m integers from an array of size n. Each element must have equal probability of being chosen.