|
|
Title | Randomize an array in Visual Basic .NET |
Description | This example shows how to randomize an array in Visual Basic .NET. |
Keywords | array, random, randomize, VB.NET |
Categories | Algorithms |
|
|
This program uses the unsorting algorithm described in my book Ready-to-Run Visual Basic Algorithms.
For each item, the algorithm randomly selects an item at that position or later in the array and swaps the two. This produces a randomized list. See my book for a proof.
|
|
Private Sub RandomizeArray(ByVal items() As Integer)
Dim max_index As Integer = items.Length - 1
Dim rnd As New Random
For i As Integer = 0 To max_index - 1
' Pick an item for position i.
Dim j As Integer = rnd.Next(i, max_index + 1)
' Swap them.
Dim temp As Integer = items(i)
items(i) = items(j)
items(j) = temp
Next i
End Sub
|
|
|
|
|
|