Problem
You are given a Java array. You need Java Code to shuffle array elements in random order.
Solution
To shuffle array elements, traverse the array and swap the current array element with another element, selected randomly.
/** * Shuffle array Java class * * @author: Ivan Georgiev */ public class ArrayShuffler { public static void shuffle(int[] targetArray) { int targetIndex; int swapBuffer; int maxInd = targetArray.length - 1; for(int curIndex=0; curIndex < targetArray.length; curIndex++) { targetIndex = (int) Math.round(Math.random() * maxInd); swapBuffer = targetArray[curIndex]; targetArray[curIndex] = targetArray[targetIndex]; targetArray[targetIndex] = swapBuffer; } } }
Discussion
The array is traversed position-by-position. For each position we swap the element into that position with randomly selected element from the array. The random selection is done using the Math.random method. By traversing all the array elements we ensure that it is “well” shuffled.
Usually we shuffle an array to produce a random selection of array elements. If the number of elements in an array is big the time necessary for shuffling the array would be significant. It would also be impossible or at least undesirable to load all the elements into memory. For that purpose it would be better to generate a list of array indexes to represent array elements.
Sample client code
Here is a simple Java application to demonstrate how the random array shuffler works.
public class ArrayShufflerTest { public static void main(String[] args) { // Define and initialize array of integers 0, 1, ..., 99 int[] arr = new int[100]; for (int i=0; i<arr.length; i++) arr[i] = i; // Display initial array System.out.println("Initial array: "); printArray(arr); // Invoke the shuffler method to shuffle the array. ArrayShuffler.shuffle(arr); // Display shuffled array System.out.println("Shuffled array: "); printArray(arr); } private static void printArray(int[] arr) { for (int el: arr) { System.out.print(el + " "); } System.out.println(); } }

Add A Comment
You must be logged in to post a comment.