|
package com.tool.code;
import java.util.Random;
public class RandomNum {
private static char ch[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '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', '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' };
//最後又重複兩個0和1,因為需要湊足數組長度為64
private static Random random = new Random();
//產生指定長度的隨機字串
public static String createRandomString(int length) {
if (length > 0) {
int index = 0;
char[] temp = new char[length];
int num = random.nextInt();
for (int i = 0; i < length % 5; i++) {
temp[index++] = ch[num & 63];
//取後面六位,記得對應的二進位是以補碼形式存在的。
num >>= 6;//63的二進位為:111111
// 為什麼要右移6位?因為數組裡面一共有64個有效字元。
//為什麼要除5取餘?因為一個int型要用4個位元組表示,也就是32位。
}
for (int i = 0; i < length / 5; i++) {
num = random.nextInt();
for (int j = 0; j < 5; j++) {
temp[index++] = ch[num & 63];
num >>= 6;
}
}
return new String(temp, 0, length);
} else if (length == 0) {
return "";
} else {
throw new IllegalArgumentException();
}
}
//根據指定個數,測試隨機字串函數的重複率
public static double rateOfRepeat(int number){
int repeat=0;
String[] str=new String[number];
for(int i=0;i<number;i++){//產生指定個數的字串
str[i]=RandomNum.createRandomString(10);
}
for(int i=0;i<number;i++){//尋找是否有相同的字串
for(int j=i+1;j<number-1;j++){
if(str[i].equals(str[j]))
repeat++;
}
}
return ((double)repeat)/number;
}
public static void main(String[] args) {
System.out.println(RandomNum.createRandomString(16)+"-"+RandomNum.createRandomString(16));
double rate=RandomNum.rateOfRepeat(10000);//測試10000次的重複率
System.out.println("重複率:"+rate);
}
}
|