1

I'd like to ask how should I implement a method in Java that takes all the elements from an array and shuffle them. Think like a deck of playing cards.

This is my try:

// a is an array of type String
public void randomize()
{
    for(int i=0; i<k; ++i)
    {
        int idx = new Random().nextInt(k);
        String random = (a[idx]);
        System.out.println(random);
    }
}
Gary
  • 13,303
  • 18
  • 49
  • 71
Amos94
  • 159
  • 1
  • 2
  • 11
  • you want to write it from scratch? – Kick Buttowski Oct 20 '14 at 19:29
  • see http://blog.codinghorror.com/the-danger-of-naivete/ for a discussion of shuffling algorithms – Alnitak Oct 20 '14 at 19:29
  • I'd like to know an idea or the methon explained. :) – Amos94 Oct 20 '14 at 19:31
  • This was answered here -> http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array – Schroed Oct 20 '14 at 19:32
  • @Alnitak it is not completely a duplicate: in the other question it is an array of primitives whereas here it is an array of objects. In particular the short and sweet `Collections.shuffle(Arrays.asList(a));` does not work with an `int[]` but does work with a `String[]`. – assylias Oct 20 '14 at 19:43

3 Answers3

1

You can use Collections.shuffle(). First convert your array to a List

Victor Grazi
  • 15,563
  • 14
  • 61
  • 94
  • It works! Thank you so much! I gave your +1! – Amos94 Oct 20 '14 at 19:44
  • Glad it worked. You might accept it as the correct answer as well. – Victor Grazi Oct 20 '14 at 21:16
  • Yes. It is the correct answer. I don't know why a guy flagged my question... before asking it I saw the other questions and none of the answers worked. However thank you so much. I learned smth new today. :) – Amos94 Oct 20 '14 at 22:42
1

Using built-in methods is probably the easiest and cleanest solution:

Collections.shuffle(Arrays.asList(a)); //shuffles the original array too

This works because the asList method (emphasis mine):

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

assylias
  • 321,522
  • 82
  • 660
  • 783
0

You mean somethin like this one? Or you are looking for something more complex?

static void shuffleArray(String[] 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;
    }
  }
Beri
  • 11,470
  • 4
  • 35
  • 57