生成随机数的算法
我希望生成一个随机数并将其发送到数据库中特定 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.
本质上的想法是做以下事情
Essentially the idea is to do the following
1) 创建一个从 0 到 9999999 的随机数
2) 检查数据库,看号码是否存在
或
2) 查询数据库中的所有数字
3) 查看返回的结果是否与来自 db
的结果匹配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),然后通过异或运算将它们传递给位,从而给我一个看似随机的数字.当然,它们并不是真正随机的,但在用户眼中它们看起来如此.
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.
附加信息
这个算法的逻辑是这样的,你使用一个已知的序列来生成唯一的数字,然后你确定性地操纵它们,所以它们看起来不再是连续的.一般的解决方案是使用某种形式的加密,在我的例子中是一个 XOR 触发器,因为它以最快的速度获得,并且满足了数字的保证永远不会碰撞.
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.
但是您可以使用其他形式的加密,如果您想要更多随机数字,超速(假设你不需要生成很多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).
[感谢 Adam Liss &CesarB 用于扩展解决方案]
[Thanks to Adam Liss & CesarB for exapanding on the solution]
相关文章