問題描述
我希望生成一個隨機數并將其發送到數據庫中特定 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) 查看返回的結果是否與來自 d??b
的結果匹配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]
這篇關于生成隨機數的算法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!