没有rand()函数的情况下如何生成随机数?

没有rand()函数的情况下如何生成随机数?

问题描述:

我想生成0到某个整数之间的(伪)随机数.我不介意他们不是太随意了.我可以访问当天的当前时间,但不能访问rand函数.谁能想到一种足够强大的方式来生成这些信息?也许,从一天中的时间中丢弃一些比特并取我的整数或其他东西作为模数?

I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my integer or something?

我正在使用c.

如果您使用的是超简单的伪随机数生成器,则可以使用

If you're after an ultra-simple pseudo-random generator, you can just use a Linear Feedback shift Register.

Wikipedia文章中有一些代码片段供您查看,但是基本上16位生成器的代码看起来应该是这样的(从该页面轻轻按摩一下...)

The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...)

  unsigned short lfsr = 0xACE1u;
  unsigned bit;

  unsigned rand()
  {
    bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;
    return lfsr =  (lfsr >> 1) | (bit << 15);
  }