在给定的一个大数列中,随机抽出一个子数列,要求所有数被抽出的概率都是一样的,如下面的运行结果:
int rangeRandNum(int a, int b) { return rand()%(b-a+1) + a; } vector<int> randPickArray(vector<int> &arr, int m) { vector<int> picks(arr.begin(), arr.begin()+m); for (int i = m; i < arr.size(); i++) { int t = rangeRandNum(0, i); if (t < m) { picks[t] = arr[i]; } } return picks; } int main() { int tar = 7; int cand[] = {1,2,3,0,3,2,0,3,1,4,5,3,2,7,5,3,0,1,2,1,3,4,6,8,1,8}; srand(time(time_t(NULL))); vector<int> v(cand, cand+sizeof(cand)/sizeof(int)); for (auto x:v) cout<<x<<" "; cout<<endl; vector<int> r = randPickArray(v, 6); for (auto x:r) cout<<x<<" "; cout<<endl; system("pause"); return 0; }