I need to randomly shuffle the following Array in Android :
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
Is there any function in the SDK to do that ?
Txs.
I need to randomly shuffle the following Array in Android :
int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
Is there any function in the SDK to do that ?
Txs.
Here's a working example. Note that the asList
method requires a list of objects. It doesn't work for primitives. So the code becomes a bit more verbose:
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main( String args[] ){
Integer[] solutionArray = {
Integer.valueOf(1),
Integer.valueOf(2),
Integer.valueOf(3),
Integer.valueOf(4),
Integer.valueOf(5),
Integer.valueOf(6),
Integer.valueOf(6),
Integer.valueOf(5),
Integer.valueOf(4),
Integer.valueOf(3),
Integer.valueOf(2),
Integer.valueOf(1)};
List solutionList = Arrays.asList( solutionArray );
System.out.println( solutionList );
Collections.shuffle( solutionList );
System.out.println( solutionList );
}
}
Using Collections to shuffle an array of primitive types is a bit of an overkill...
It is simple enough to implement the function yourself, using for example the Fisher–Yates shuffle:
import java.util.*;
class Test
{
public static void main(String args[])
{
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };
shuffleArray(solutionArray);
for (int i = 0; i < solutionArray.length; i++)
{
System.out.print(solutionArray[i] + " ");
}
System.out.println("");
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i >= 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
Here is a simple way using ArrayLists
ArrayList<Integer> cards = new ArrayList<Integer>();
for(int i=1;i<=52;i++)
{
this.cards.add(i);
}
Collections.shuffle(this.cards);