如何在随机发生器中获得50/50的机会 [英] How to get a 50/50 chance in random generator
本文介绍了如何在随机发生器中获得50/50的机会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在随机生成器中获得50或50的机会获得1或2。
I am trying to get a 50/50 chance of get either 1 or 2 in a random generator.
例如:
Random random = new Random();
int num = random.nextInt(2)+1;
此代码将输出1或2.
This code will output either a 1 or 2.
假设我在一个循环中运行它:
Let's say I run it in a loop:
for ( int i = 0; i < 100; i++ ) {
int num = random.nextInt(2)+1 ;
}
如何让生成器为1和2赋予相同的数字case?
How can I make the generator make an equal number for 1 and 2 in this case?
所以我希望这个循环产生50倍的1号和50倍的2号。
So I want this loop to generate 50 times of number 1 and 50 times of number 2.
推荐答案
一种方法:用50个1和50个2填充 ArrayList< Integer>
,然后调用 Collection。 shuffle(...)
就可以了。
One way: fill an ArrayList<Integer>
with fifty 1's and fifty 2's and then call Collection.shuffle(...)
on it.
这篇关于如何在随机发生器中获得50/50的机会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文