[英]Generating a list of random numbers in java
I generate a random number 0 or 1 我生成一个0或1的随机数
int randomColor = (Math.random() < 0.5) ? 0 : 1;
I need to create 52 random numbers and 26 of them will be 0 and 26 are 1 我需要创建52个随机数,其中26个为0,26个为1
You can do this: Create a List
of 52 numbers. 您可以这样做:创建一个包含52个数字的List
。 Fill it with 26 zeroes and 26 ones, and then use Collections.shuffle()
to shuffle them in a random order. 用26个零和26个填充它,然后使用Collections.shuffle()
以随机顺序对它们进行混洗。
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < 26; i++) {
numbers.add(0);
numbers.add(1);
}
Collections.shuffle(numbers);
Use Collections.shuffle(list)
and just 3 lines of code for the whole thing: 使用Collections.shuffle(list)
,只需3行代码即可:
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 52; i++) list.add(i % 2);
Collections.shuffle(list);
Voila! 瞧!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.