有效地选择随机数

Frederik Wordenskjold:

我有一种方法,它使用随机样本来近似计算。这种方法被称为数百万次,因此非常重要的是选择随机数的过程必须高效。

我不确定java到底有多快Random().nextInt,但是我的程序似乎并没有像我期望的那样受益。

选择随机数时,我将执行以下操作(半伪代码):

// Repeat this 300000 times
Set set = new Set();
while(set.length != 5)
    set.add(randomNumber(MIN,MAX));

现在,这显然具有最坏的最坏情况下的运行时间,因为理论上随机函数可以为永恒添加重复的数字,从而永远停留在while循环中。但是,数字是从{0..45}中选择的,因此重复的值在大多数情况下是不可能的。

当我使用上述方法时,其速度仅比我的其他方法快40%,该方法虽然不近似,但可以得出正确的结果。这个过程运行了大约一百万次,因此我期望这种新方法至少快50%。

您对更快的方法有什么建议吗?或者,也许您知道一种生成一组随机数的更有效方法。

为了澄清,这是两种方法:

// Run through all combinations (1 million). This takes 5 seconds
 for(int c1 = 0; c1 < deck.length; c1++){
    for(int c2 = c1+1; c2 < deck.length; c2++){
     for(int c3 = c2+1; c3 < deck.length; c3++){
        for(int c4 = c3+1; c4 < deck.length; c4++){
         for(int c5 = c4+1; c5 < deck.length; c5++){
             enumeration(hands, cards, deck, c1, c2, c3, c4, c5);
         }
            } 
      }     
   }
   }

// Approximate (300000 combinations). This takes 3 seconds
Random rand = new Random();
HashSet<Integer> set = new HashSet<Integer>();
int[] numbers = new int[5];
while(enumerations < 300000){
set.clear();
while(set.size() != 5){
    set.add(rand.nextInt(deck.length));
}
Iterator<Integer> i = set.iterator();
int n = 0;
while(i.hasNext()){
    numbers[n] = i.next();
    n++;
}

经过一些测试和分析,我发现这种方法是最有效的:

Random rand = new Random();
int[] numbers = new int[5];
ArrayList<Integer> list = new ArrayList<Integer>();
while(enumerations < 300000){
 while(list.size() != 5) {
     int i = rand.nextInt(deck.length);
        if(!list.contains(i)) list.add(i);
 }
 int index = 0;
 for(int i : list){ numbers[index] = i; index++; }
 enumeration(hands, cards, deck,numbers);
}
尤瓦尔·亚当(Yuval Adam):

您可以尝试将现有的Java实现或该实现)用于Mersenne Twister

请记住,大多数MT 都不是加密安全的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章