ProblemYou want to randomize the order of the elements in an array efficiently. SolutionSample code folder: Chapter 08\ShuffleArray Write a routine that randomly rearranges the elements of an array. The code in this recipe does this using an array of any data type. DiscussionThe Shuffle() method presented here swaps each element of the array with a randomly selected element from elsewhere in the array. Sometimes this may cause an element to be swapped with itself, but that doesn't make the results any less random. By sequencing through all elements, the algorithm guarantees that each one will be swapped at least once: Public Sub Shuffle(ByRef shuffleArray( ) As Object) ' ----- Reorder the elements of an array in a random order. Dim counter As Integer Dim newPosition As Integer Dim shuffleMethod As New Random Dim tempObject As Object For counter = 0 To shuffleArray.Length - 1 ' ----- Determine the new position. newPosition = shuffleMethod.Next(0, _ shuffleArray.Length - 1) ' ----- Reverse two elements. tempObject = shuffleArray(counter) shuffleArray(counter) = shuffleArray(newPosition) shuffleArray(newPosition) = tempObject Next counter End Sub The following code creates a string array of fruit names, shuffles the array, and displays the array contents both before and after the shuffling: Dim result As New System.Text.StringBuilder Dim arrayShuffle( ) As String = { _ "Oranges", "Apples", "Grapes", "Bananas", "Blueberries"} ' ----- Show the pre-random results. result.AppendLine("Before shuffling:") For Each fruit As String In arrayShuffle result.AppendLine(fruit) Next fruit ' ----- Randomize. Shuffle(arrayShuffle) ' ----- Show the post-random results. result.AppendLine( ) result.AppendLine("After shuffling:") For Each fruit As String In arrayShuffle result.AppendLine(fruit) Next fruit MsgBox(result.ToString( )) Figure 8-5 shows the results from running the sample code, listing the array's contents before and after the shuffling. Your output may vary due to the random nature of the test. Figure 8-5. Randomizing an array's elements with the Shuffle( ) methodSee AlsoRecipe 8.6 uses a portion of this recipe's code to generically reverse two array elements. |