In java, what I should do the create an array with half of data is 0s, half 1s? And what I should do to use Randomize (shuffle) the contents of the array
Asked
Active
Viewed 93 times
-3
-
7Start by building array, adding 50% as `0` and 50% as `1`. Then use `Collections.asList` and `Collections.shuffle` to randomise it – MadProgrammer Feb 15 '18 at 23:48
-
2Do you mean *exactly* **half** of 0s and 1s? – zlakad Feb 15 '18 at 23:48
2 Answers
2
Integer[] arr = new Integer[100];
Arrays.fill(arr, 0, 50, 0);
Arrays.fill(arr, 50, 100, 1);
List<Integer> list = Arrays.asList(arr);
Collections.shuffle(list); //list is now in random order
If you want to avoid using a Integer
and List
for the sake of Collections.shuffle()
, you'd need to implement the shuffling yourself. See this question for that.

Malt
- 28,965
- 9
- 65
- 105
0
Try this.
int size = 100;
List<Integer> list = IntStream.range(0, size).mapToObj(x -> x).collect(Collectors.toList());
Collections.shuffle(list);
int[] result = list.stream().mapToInt(x -> x % 2).toArray();