JavaScript pseudo-random sequence generator

若如初见. 提交于 2019-12-01 08:07:09

There are some good int -> int hashing functions on this page you can use one of them.

function hash(a)
{
    a = (a+0x7ed55d16) + (a<<12);
    a = (a^0xc761c23c) ^ (a>>19);
    a = (a+0x165667b1) + (a<<5);
    a = (a+0xd3a2646c) ^ (a<<9);
    a = (a+0xfd7046c5) + (a<<3);
    a = (a^0xb55a4f09) ^ (a>>16);
    if( a < 0 ) a = 0xffffffff + a;
    return a;
}
var seed = 26254;
var index = 250;
alert( hash( seed + index ) );

In the end I used a suggestion from a (non-SO) friend. I went with CRC32() as this is extremely fast and gives decently random values.

return crc32(seq + seed) % maxVal;

A run of eight million produced the following distribution for maxVal = 8:

0 999998

1 999998

2 1000007

3 1000003

4 1000001

5 1000003

6 999992

7 999998

I also ran "Marsaglia's famous "Die Hard" battery of tests" mentioned in the Donald Knuth page Hans mentioned, the results of which are here: CRC32() for random numbers Diehard results. The short version is that it fails miserably (for such a small amount of test data), but it's still good enough for my needs where it is generating numbers in a small range.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!