Rearrange array. Make 1, 3, 5 to 3, 5, 1 and etc
Let's say I have an array:
int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
How can I randomly make it
int array[][] = {{2, 5, 7}, {1, 2, 3}, {4, 2, 1}};
or
int array[][] = {{4, 2, 1}, {2, 5, 7}, {1, 2, 3},};
And so on.开发者_如何学编程
Is there any JAVA function to help me? Or I have to figure it out by myself?
Thank you.
You might convert your array to a List<int[]>
and call Collections.shuffle()
. Then convert back to an array.
int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
List<int[]> l = Arrays.asList( array ); //the list returned is backed by the array, and thus the array is shuffled in place
Collections.shuffle( l );
//no need to convert back
If you need to keep the original order, you'd have to create a copy of the array (or the list backed by that array), like this:
int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
List<int[]> l = new ArrayList<int[]>( Arrays.asList( array ) ); //creates an independent copy of the list
Collections.shuffle( l );
int newArray[][] = l.toArray( new int[0][0] );
Another way:
int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
int newArray[][] = array.clone(); //copy the array direcly
List<int[]> l = Arrays.asList( newArray );
Collections.shuffle( l );
It is very simple using the Collections.shuffle(..)
method as the Arrays.asList(..)
method returns a List backed by the array
.
Collections.shuffle(Arrays.asList(array));
Full example:
public static void main(String... args) {
int array[][] = {{1, 2, 3}, {2, 5, 7}, {4, 2, 1}};
Collections.shuffle(Arrays.asList(array));
for (int[] a : array)
System.out.println(Arrays.toString(a));
}
If you can use collections there is a shuffle method, if you have to use a primitive type such as int, you will have to shuffle it yourself. Here are examples of both:
http://blog.ryanrampersad.com/2008/10/13/shuffle-an-array-in-java/
Try the Collections class that comes with Java. You can use the shuffle() method to randomize the indices to access the arrays.
Link to Java API
Use Collections: something like this:
List<int[]> list = Arrays.asList(array);
Collections.shuffle(list);
int[][] shuffledArray = (int[][]) shuffledList.toArray();
What you want is random swaps of the contents of the outer array.
You could use java.Random's nextBoolean() to get a true/false as to whether to make a swap, such as between 1&2 or 1&3 or 2&3.
This is assuming you want to work with the primitive types, and not classes.
精彩评论