![](/img/trans.png)
[英]How can I get the multiple attributes according to unique ids in MongoDB?
[英]how many unique ids can be generated
我正在使用以下代碼創建一個唯一的ID,該ID為8個字符(包括數字和字母數字字符)。
try {
List<String> uuidList = new ArrayList<String>();
int counter = 1;
File file = new File("D://temp//temp1.txt");
file.createNewFile();
Writer writer = new FileWriter(file);
BufferedWriter wr = new BufferedWriter(writer);
while(true) {
int length = bitsArray.length;
Random r = new Random();
StringBuffer uuid = new StringBuffer();
for(int i= 0; i < 8; i++) {
int nextRandomId = r.nextInt(length);
uuid.append(bitsArray[nextRandomId]);
}
String uuidString = uuid.toString();
wr.write(uuidString);
wr.newLine();
if(counter != 1 && uuidList.contains(uuidString)) {
Thread.sleep(1000);
System.err.println(counter);
break;
}
//061e735145fc
System.err.println(uuidString);
uuidList.add(uuidString);
counter++;
}
} catch (Exception e) {
}
我需要知道,如果我使用上面的代碼..那么我可以生成多少個唯一的ID。 給定
static String[] bitsArray = {"a","b","c","d","e","f","g","h","i",
"j","k","l","m","n","o","p","q","r",
"s","t","u","v","w","x","y","z",
"0","1","2","3","4","5","6","7","8","9"};
請幫忙..
本質上,總共可以生成36 8個字符串。
通過使用離散數學 (使用位字符串)來解釋該定理:
您有8個字符的位字符串,需要填寫36個字符中的1個:
__ __ __ __ __ __ __ __
36 36 36 36 36 36 36 36 (characters a -- z, 0-- 9)
因此,您有36*36*36*36*36*36*36*36
= 36 8 = 2,821,109,907,456
總ID。
(26 + 10)^ 8 = 2821109907456
在這里看看:
Permutations with Repetition
區間Permutations with Repetition
。 從理論上講,給定一組n
元素(即bitsArray
的長度)並且排列的長度(即uuidString
字符串)為r
,您將能夠生成n ^ r個唯一的排列(即您的情況下的UUID)。
在您的情況下,n = 36(26個字母和10個數字)且r = 8(uuid的長度為8),因此為:
36^8 = 2821109907456
有多少個唯一ID? 大約一百萬 這取決於您使用的隨機數生成器的質量。 如果該隨機數生成器始終返回4 ,則只能生成一個標識符。 如果它是一個低質量的線性同余生成器(對於較低的位具有相當差的隨機性),您最終得到的值將比理論最大值(36 8 =約2.8萬億)少256倍。 但是,由於您生成的每個ID都需要讀取以前生成的ID的整個列表,因此我懷疑您的計算機在達到一百萬個標識符之前只會擺脫困境。
多少個UUID? 零。 您的代碼依靠內部黑名單來避免沖突,這意味着使用您的方法生成UUID的多台計算機有相當合理的機會以沖突結尾(避免沖突首先是使用UUID的全部內容)。
[number of possible char]^[lenght of the generatet id]
-非常簡單的數學
在您的情況下:
36^8 = 2821109907456
數組的長度為36。使用方法r.nextInt(length)
意味着隨機數的最大值為36,從0到35。因此最多可以獲得8個索引36。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.