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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With