我从几个字符串数组中随机生成单词。
有4个长度为7、9、15和24的数组。
这意味着有22680个可能的排列。在此基础上,我在字符串的末尾添加了一个0-999的数字,这意味着我将可能的排列乘以999,得到了2200多万个组合。
我用一个列表来评估碰撞的频率,得到了一些非常低的数字。在找到重复的字符串之前,我从来没有做过超过10000次的迭代。
String[][] dictionary = // array of 4 string arrays
public String assemble() {
StringBuffer sb = new StringBuffer(30);
for(int i=0; i<4; i++) {
// for each strArr, select a random element
sb.append(select(dictionary[i]));
}
// add a number from 0 - 999 to the end of the string
sb.append(randInt(999));
return sb.toString();
}
private String select(String[] strArr) {
return strArr[randInt(strArr.length)];
}
List<String> generatedStrings = new ArrayList<>();
List<Integer> iterations = new ArrayList<>();
// iterate until the same string is generated twice or we make 1M strings
for (int i = 0; i < 1000000; i++) {
String s = assemble();
if (generatedStrings.contains(s)) {
iterations.add(i);
generatedStrings.clear();
break;
}
generatedStrings.add(s);
}
生成随机整数的方法:
SecureRandom secureRandom = new SecureRandom();
public int randInt(int length) {
return secureRandom.nextInt(length);
// also tried the following, though I think the underlying tech is the same:
// return (int) (Math.random() * length);
}
当我在main方法中运行这个时,得到的数字大约是13k,这看起来很低。这是我生成随机数的方式的问题吗?
暂无答案!
目前还没有任何答案,快来回答吧!