如何评估java应用程序的随机性?

sauutmhj  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(209)

我从几个字符串数组中随机生成单词。
有4个长度为7、9、15和24的数组。
这意味着有22680个可能的排列。在此基础上,我在字符串的末尾添加了一个0-999的数字,这意味着我将可能的排列乘以999,得到了2200多万个组合。
我用一个列表来评估碰撞的频率,得到了一些非常低的数字。在找到重复的字符串之前,我从来没有做过超过10000次的迭代。

  1. String[][] dictionary = // array of 4 string arrays
  2. public String assemble() {
  3. StringBuffer sb = new StringBuffer(30);
  4. for(int i=0; i<4; i++) {
  5. // for each strArr, select a random element
  6. sb.append(select(dictionary[i]));
  7. }
  8. // add a number from 0 - 999 to the end of the string
  9. sb.append(randInt(999));
  10. return sb.toString();
  11. }
  12. private String select(String[] strArr) {
  13. return strArr[randInt(strArr.length)];
  14. }
  15. List<String> generatedStrings = new ArrayList<>();
  16. List<Integer> iterations = new ArrayList<>();
  17. // iterate until the same string is generated twice or we make 1M strings
  18. for (int i = 0; i < 1000000; i++) {
  19. String s = assemble();
  20. if (generatedStrings.contains(s)) {
  21. iterations.add(i);
  22. generatedStrings.clear();
  23. break;
  24. }
  25. generatedStrings.add(s);
  26. }

生成随机整数的方法:

  1. SecureRandom secureRandom = new SecureRandom();
  2. public int randInt(int length) {
  3. return secureRandom.nextInt(length);
  4. // also tried the following, though I think the underlying tech is the same:
  5. // return (int) (Math.random() * length);
  6. }

当我在main方法中运行这个时,得到的数字大约是13k,这看起来很低。这是我生成随机数的方式的问题吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题