生成"在动态范围和QUOT;用C随机数 [英] Generate "In-Range" Random Numbers in C

查看:116
本文介绍了生成"在动态范围和QUOT;用C随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的范围内产生的随机数[0,10],使得:

I need to generated random numbers in the range [0, 10] such that:


  • 出现一次所有的数字。

  • 没有重复的结果得以实现。

有人能指导我用哪种算法?

Can someone please guide me on which algorithm to use?

推荐答案

在理查德·罗斯的答案算法不正确。它生成ñ^ N 可能的排序,而不是 N!。这个职位上杰夫阿特伍德的博客说明了这个问题:<一href=\"http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html\">http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

The algorithm in Richard J. Ross's answer is incorrect. It generates n^n possible orderings instead of n!. This post on Jeff Atwood's blog illustrates the problem: http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html

相反,你应该使用高德纳 - 费雪耶茨洗牌:

Instead, you should use the Knuth-Fisher-Yates Shuffle:

int values[11] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
srand(time(NULL));

for (int i = 10; i > 0; i--)
{
    int n = rand() % (i + 1);

    int temp = values[n];
    values[n] = values[i];
    values[i] = temp;
}

这篇关于生成&QUOT;在动态范围和QUOT;用C随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆