Java – print arrays in random order
•
Java
See English answers > random shuffling of an array 27
Example:
int [] myArray = {5,4,3,2,1};
When printing, the result may be:
3 2 1 4 5
or
4 3 2 5 1
Solution
You should read and write a fisher Yates shuffle It's easy and efficient In fact, you can logically partition the array into "shuffled" and "unwashed" – then repeatedly select a random element from the unwashed part and exchange it with the first element in the unwashed part to form part of the shuffle part
Alternatively, create a list < integer > instead, and use collections shuffle. Unfortunately, there is no corresponding array, but the Java type system does not do well in making arrays or primitives universal:(
(I assume you know how to print, and this is a very difficult aspect for you.)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码