今天我们宿舍三人同台演出了这一个算法的实现! 总得来说,尚未有令三方都满意的算法! 我将代码贴上来,希望有朝一日能找到号称perfect的算法! 随机从数组里取n个不重复的数! 我的算法1 #include <iostream> #include <time.h> #include <cstdlib> using namespace std; void swap(int &a,int &b) { int temp = a; a = b; b = temp; } int main() { srand(time(0)); int a[10] = {1,2,3,4,5,6,7,8,9,10}; int t,x=0; for(int i=9;i>=0;i–){ if(x<6){ t=rand()%(i+1); cout<<a[t]<<” “; swap(a[t],a[i]); x++; } } cout<<endl; for(int i =0;i<10;i++) cout<<a[i]<<” “; return 0; } //随机从数组里取n个不重复的数! 算法2 #include <cstdlib> //#include <time.h> #include <iostream> using namespace std; #define N 15 void HashRnd(int *p) { int array[N]; for(int i = 0; i < N; ++i){ array[i] = i ; } int n = N; for(int pos = 0; pos < N; ++pos){ int i = rand()%n–; p[pos] = array[i]; array[i] = array[n]; } } int main() { int p[15]; HashRnd(p); for(int i =0;i<15;i++) cout<<p[i]<<” “; return 0; } //随机从数组里取n个不重复的数! 我舍友 linxy的算法 #include<iostream> #include <time.h> #include <algorithm> #include<stdlib.h> using namespace std; const int MAX = 100; /* void swap(int &a,int &b) { int temp = a; a = b; b = temp; }*/ int main() { int x; // static const int size = 10; int a[MAX]; for(int i=0; i!=MAX; i++) a[i] = i; // for(int i = 1;i<=10;i++){ // x = (rand()%(11-i)) + i; // swap(a[x-1],a[10-x-1]); // } srand(time(0)); int n = MAX; int m = 4; for(int i=0; i!=MAX; i++,n–){ if(rand()%n<50){ cout << a[i] << ” “; m–; if(m==0) break; } } // for(int j = 0;j!=10;j++) // cout<<a[j]<<” “; return 0; }