您的位置:首页 > 其它

生成k个不同的随机数(1-n)

2014-06-10 14:43 162 查看
《编程珠玑》习题1.4:如果认真考虑了习题3,你将会面对生成小于n且没有重复的k个整数的问题。最简单的方法就是使用前k个正整数。这个极端的数据集合将不会明显的改变位图方法的运行时间,但是可能会歪曲系统排序的运行时间。如何生成位于0至n - 1之间的k个不同的随机顺序的随机整数?尽量使你的程序简短高效。

(题目copy from http://blog.chinaunix.net/uid-21228455-id-2406483.html)
我找到最好的方法:Fisher-Yates shuffle

(http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdio>
using namespace std;
#define N 10
/*
To shuffle an array a of n elements (indices 0..n-1):
for i from n − 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
*/
void generateRandom1(int *random){
for(int i = N-1; i >= 1; --i){
int j = rand()%(i+1);
std::swap(random[i], random[j]);
}
}
int main() {
int random
;
for(int i = 0;i < N; ++i)
random[i] = i;
srand(time(NULL));
generateRandom1(random);
for(int i = 0;i < N; ++i)
cout << random[i] << " ";
cout << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: