Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a list of random numbers in java

Tags:

java

random

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

like image 743
Max Usanin Avatar asked Mar 28 '13 06:03

Max Usanin


2 Answers

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);
like image 139
Jesper Avatar answered Oct 29 '22 18:10

Jesper


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!

like image 38
Bohemian Avatar answered Oct 29 '22 16:10

Bohemian