Question:
How to shuffle an array in java?
Code:
import java.util.*; public class ShuffleCards { public static void main(String[] args) { Random r = new Random(); int[] cards = new int[10]; // Initialize the array to the ints 0-51 for (int i=0; i < cards.length; i++) { cards[i] = i; } // print out contents of array System.out.println(Arrays.toString(cards)); // Shuffle by exchanging each element randomly for (int i=0; i < cards.length; i++) { int pos = r.nextInt(cards.length); int temp = cards[i]; cards[i] = cards[pos]; cards[pos] = temp; } // print out contents of array System.out.println(Arrays.toString(cards)); } }
Output:
$ java ShuffleCards [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [1, 2, 3, 4, 9, 7, 8, 5, 0, 6]