Open source random number generation algorithm in

2019-04-07 17:15发布

I need to generate random numbers in the range 1 - 10000 continuously with out duplication. Any recommendations?

Description: we are building a new version for our application, which maintains records in Sqlite DB. in the last version of our application, we did not had unique key for each record. But now with new upgraded version, we need to support the import facility from the last version's DB. So what we do is, we read each and every record from the old DB and generate a random number for the unique key and store it in new DB. Here we many need to import up to 10000 records continuously.

14条回答
神经病院院长
2楼-- · 2019-04-07 18:03

Boost.Random is a good choice and works fine for me. However, if you don't need many random number generators and distributions you may look for another library just not to install the whole Boost package.

查看更多
干净又极端
3楼-- · 2019-04-07 18:03

Generate large random numbers. Say 128 bits. The odds of two such numbers being the same in a set of 10000 are ridiculously small (on the order of n^2/2^b, where n = number of numbers needed and b = number of bits used). Given enough bits, the odds will become smaller than the odds of your ram being corrupted by a cosmic ray such that your algorithm fails anyway. Be careful that the space you are drawing the random numbers from really has the number of bits you are looking for. It is easy to mistakenly generate 128 bit numbers from a pool of 32 bits (i.e., there are only 2^32 possibilities even though you are generating numbers 1 through 2^128). The random number generators in the boost library can do this correctly for you. BTW: if you don't like 128 bits, then use 256 bits or more until you are comfortable that there is no practical chance of a hashing collision. If you only have to do this once, then just use the shuffle method already mentioned in a previous answer. That will have the advantage of generating a perfect hash.

查看更多
The star\"
4楼-- · 2019-04-07 18:04

Is it ok to question the whole idea of using a random number as the unique key for database record? I'm not familiar with sqlite, but it's worth investigating whether it supports some kind of unique column identifier internally. SQL Server has 'identity' columns, for example, and Oracle has 'sequences', both of which serve the same purpose.

查看更多
时光不老,我们不散
5楼-- · 2019-04-07 18:04

The generation of random numbers is too important to be left to chance. -- Robert R. Coveyou, Oak Ridge National Laboratory

查看更多
Rolldiameter
6楼-- · 2019-04-07 18:06

http://random.org/ if you need truly random numbers

查看更多
一夜七次
7楼-- · 2019-04-07 18:08

While you may have a requirement to generate a sequence of values that do not repeat, you cannot call the result "random". True randomness has less to do with lack of repetition than it has to do with the distribution of values in a sequence.

查看更多
登录 后发表回答