关于从数组随机抽取一组数的东东!
2009-04-25 10:05
363 查看
今天我们宿舍三人同台演出了这一个算法的实现!
总得来说,尚未有令三方都满意的算法!
我将代码贴上来,希望有朝一日能找到号称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 ; 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 ; } } 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; }
相关文章推荐
- 关于从list或者数组中随机抽取部分不重复元素的问题探究
- 随机抽取到数组
- 关于生成一个随机数组
- 穷举法&在给定一组字符中随机抽取字符的方法
- 从数组中抽取随机成员
- 关于生成不重复随机数组的问题?
- php数组随机抽取函数shuffle()和array_rand()
- 随机从数组或集合中抽取一个值或 从list集合中随机抽几个值 或算权重
- 数组与集合的应用之数组演练(利用数组随机抽取幸运观众)
- 几个关于随机数组产生的函数 包括各类可重复或不重复
- 关于一道 产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复
- 【实践】js实现随机不重复抽取数组中元素
- 关于生成一个随机数组
- 关于 JavaScript 的数组随机排序
- 随机从长度未知的数组中抽取数字,且保证每个元素被抽到的概率相同
- 数组例子:利用数组随机抽取幸运观众
- 从数组和List中随机抽取若干不重复的元素.
- php 数组 高效随机抽取指定条记录的算法
- Java利用数组随机抽取幸运观众
- 关于JavaScript的数组随机排序