简体   繁体   中英

Generating a list of random numbers in java

I generate a random number 0 or 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

You can do this: Create a List of 52 numbers. Fill it with 26 zeroes and 26 ones, and then use Collections.shuffle() to shuffle them in a random order.

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:

List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 52; i++) list.add(i % 2);
Collections.shuffle(list);

Voila!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM