算法产生随机数 [英] Algorithm for generating a random number

查看:133
本文介绍了算法产生随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我期待产生一个随机数,并发出到一个表中的某一特定user_ID的数据库。渔获,相同数量不能使用两次。有一个亿的方法来做到这一点,但我希望有人非常热衷于算法具有在以下标准的一流解决方案解决这个问题的一个聪明的办法得到满足:

I'm looking to generate a random number and issue it to a table in a database for a particular user_id. The catch is, the same number can't be used twice. There's a million ways to do this, but I'm hoping someone very keen on algorithms has a clever way of solving the problem in an elegant solution in that the following criteria is met:

1)是由最少量的查询的数据库。 2)由该至少量通过在存储器中的数据结构的爬行

1) The least amount of queries to the database are made. 2) The least amount of crawling through a data structure in memory is made.

本质的想法是做好以下

1)创建一个随机数从0到9999999
2)检查数据库,查看是否存在一些
    或
2)查询数据库中的所有数字
如果从数据库 4)如果匹配,重复步骤1,如果不是,问题就解决了​​。

1) Create a random number from 0 to 9999999
2) Check the database to see if the number exists
OR
2) Query the database for all numbers
3) See if the returned result matches whatever came from the db
4) If it matches, repeat step 1, if not, problem is solved.

感谢。

推荐答案

没有你的算法是不可扩展的。什么我以前做的就是连续发出数(每次+1),然后把它们通过XOR操作混杂从而给我一个看似随机数的位。当然,他们并不是真正随机的,但他们看起来那么对用户的眼睛。

No your algorithm is not scalable. What I've done before is to issue numbers serially (+1 each time) and then pass them through an XOR operation to jumble the bits thus giving me a seemingly random numbers. Of course they aren't really random, but they look so to users eyes.


其他信息

该算法的逻辑是这样的,你使用一个已知序列 生成唯一的号码,然后你确定性操纵它们, 所以他们不看串行了。一般的解决方案是使用 某种形式的加密,这在我的情况下,是一个异或触发器,因为 它以最快的速度,因为它可以得到的,它满足了保证号码 决不会发生碰撞。

This algorithm's logic goes like this you use a known sequence to generate unique numbers and then you deterministically manipulate them, so they don't look serial anymore. The general solution is to use some form of encryption, which in my case was an XOR flipflop, because its as fast as it can get, and it fulfills the guarantee that numbers will never collide.

但是可以使用其他形式的加密,如果你更想preFER 随机找数,超速(说你不需要产生许多 的ID的时间)。现在,在选择加密算法的重要一点 是保证数量将永远不会发生冲突。和一种方法来证明,如果加密算法可以完成 这一保证是检查原数目和结果两个 加密有相同的比特数,并且该算法是 可逆(双向注入​​)。

However you can use other forms of encryption, if you want prefer even more random looking numbers, over speed (say you don't need to generate many ids at a time). Now the important point in choosing an encryption algorithm is "the guarantee that numbers will never collide". And a way to prove if an encryption algorithm can fulfill this guarantee is to check if both the original number and the result of the encryption have the same number of bits, and that the the algorithm is reversible (bijection).

[感谢为亚当·利斯&放大器; CesarB 作为exapanding的解决方案]

[Thanks to Adam Liss & CesarB for exapanding on the solution]

这篇关于算法产生随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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