views:

610

answers:

4

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.

+2  A: 

Look at the Collections class, specifically shuffle(...)

Dave
How do you use this Collections class in Android ? You need to do a special import (CRTL SHIT O doesn't work) to use it ?
Hubert
+2  A: 

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 );
   }

}
exhuma
I copied your two lines and did :import java.util.ArrayList;import java.util.Arrays;import java.util.List;Syntax error on token "solutionList", VariableDeclaratorId expected after this token...
Hubert
Edited the code. This should now provide a working example.
exhuma
txs, I'll read this first to see how to correctly use it: http://java.sun.com/docs/books/tutorial/collections/index.html
Hubert
+1  A: 

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;
    }
  }
}
PhiLho
Txs PhiLho, that's what I did at the end.
Hubert
Extremely trivial nitpick, but you can just use `println()` instead of `println("")`. Clearer in intent I think :)
Cowan
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);
methodin