我有一个方法,它使用随机样本近似计算。这种方法被称为数百万次,所以选择随机数的过程非常重要。有效选择随机数
我不知道Java类的速度有多快Random().nextInt
真的,但我的计划似乎并没有那么多好处,我想这一点。
当选择随机数,我做了以下(处于半伪代码):
// Repeat this 300000 times
Set set = new Set();
while(set.length != 5)
set.add(randomNumber(MIN,MAX));
现在,这显然有不好的最坏情况下的运行时间,因为在理论上随机功能为永恒添加重复的数字,从而永远留在while循环中。但是,这些数字是从{0..45}中选择的,因此重复值大多数情况下不太可能。
当我用上面的方法,比我的另一种方法,它不接近它的速度只有40%,但产生正确的结果。这是大约100万次,所以我期待这种新方法至少快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);
}
你能再说一遍是什么,你要完成?你是否试图用每个方法调用生成一组N个不同的数字?你谈论的是将这种方法与另一个“不近似”而另一种方法更快 - 是真正的问题随机数生成还是用于其他计算(近似与非近似)的方法? – 2010-03-26 13:32:47
问题是随机数字的产生。其他计算不相关,这就是为什么我没有提到他们在我的问题。 – 2010-03-26 13:40:32