产生随机数的阵列中与QUOT一个给定的范围内; C" [英] To generate array of random numbers in a given range in "C"
问题描述
我想生成例如随机数的数组,如果范围为[0,10],然后期望的输出是
2 3 5 6 4 7 8 9 0 1(非repeatitive)
i want to generate an array of random numbers for example if the range is [0,10] then the desired output to be 2 3 5 6 4 7 8 9 0 1 ( non repeatitive )
我与rand()函数所面临的问题是,有时我得到一些重复的号,我是在这个范围内离散值,和不同的顺序,每次我调用。
the problem i am facing with rand() function is sometimes i get some repeated nos , i was discrete values in that range , and different order everytime i invoke.
PS:我没通过一些线程
<一href=\"http://stackoverflow.com/questions/3680637/how-to-generate-a-random-double-in-a-given-range\">How以产生在给定的范围的随机双
http://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-entire-range
在这里不可能精种相似矿,有细微的差别。 expecially后者是pretty关闭
Ps: I did go through some of the threads How to generate a random double in a given range http://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-entire-range in here and couldnt fine one similar mine, there is a subtle difference. expecially the latter one is pretty close
推荐答案
这似乎更是洗牌随机化的问题。
It seems more a problem of shuffling that of randomization.
一个良好的开端是在费雪耶茨洗牌这与元素的数组排序开始,并生成一个随机排列:
A good start is the Fisher-Yates shuffle which starts with the sorted array of elements and generate a random permutation:
int size = 10;
int *elements = malloc(sizeof(int)*size);
// inizialize
for (int i = 0; i < size; ++i)
elements[i] = i;
for (int i = size - 1; i > 0; --i) {
// generate random index
int w = rand()%i;
// swap items
int t = elements[i];
elements[i] = elements[w];
elements[w] = t;
}
这篇关于产生随机数的阵列中与QUOT一个给定的范围内; C&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!