思想:先以m/n的概率判斷第一個數出不出現;如果出現,那麼以(m-1)/(n-1)的概率判斷下一個數出不出現;若不出現,那麼以m/n-1的概率判斷下一個數出不出現,等於如果前面的數不出現的話加大後面的數的出現概率。
#include "iostream"
#include "ctime"
#include "cstdlib"
using namespace std;
void knuth(int n, int m){
srand((unsigned int) time(0));
for (int i = 0; i < n; i++){
if ( rand() % (n - i) < m) {
cout << i << endl;
m--;
}
}
}
int main(){
knuth(10,8);
}