Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to randomize an array of ints in Java

Is it possible to choose a random element from one array and move it to another without the aid of ArrayLists/Collections etc (unless you can use shuffle on an array)? and making sure that element isn't selected again? I thought about setting it to null seems you cannot remove it but I'm unsure.

Basically i want myArray to get shuffled or randomized and I figured the best way would be to pull them from one in a random order and add them to a new one...

like image 605
binary101 Avatar asked Dec 21 '22 12:12

binary101


1 Answers

You can use Collections.shuffle(List) to shuffle an array as well:

Integer[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Collections.shuffle(Arrays.asList(data));

System.out.println(Arrays.toString(data));

will print e.g. [6, 2, 4, 5, 10, 3, 1, 8, 9, 7].

Arrays.asList will not create a new list, but a List interface wrapper for the array, so that changes to the list are propagated to the array as well.

like image 54
jarnbjo Avatar answered Feb 28 '23 10:02

jarnbjo