Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to randomize a list in VB.NET?

I have a list of type System.IO.FileInfo, and I would like to randomize the list. I thought I remember seeing something like list.randomize() a little while back but I cannot find where I may have seen that.

My first foray into this yielded me with this function:

Private Shared Sub GetRandom(ByVal oMax As Integer, ByRef currentVals As List(Of Integer))
    Dim oRand As New Random(Now.Millisecond)
    Dim oTemp As Integer = -1
    Do Until currentVals.Count = IMG_COUNT
        oTemp = oRand.Next(1, oMax)
        If Not currentVals.Contains(oTemp) Then currentVals.Add(oTemp)
    Loop
End Sub

I send it the max val I want it to iterate up to, and a reference to the list I want the randomized content in. The variable IMG_COUNT is set farther up in the script, designating how many random images I want displayed.

Thanks guys, I appreciate it :D

like image 546
Anders Avatar asked Feb 16 '09 21:02

Anders


People also ask

What does Randomize() do in Visual Basic?

Randomize uses Number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit Number , the value returned by the system timer is used as the new seed value.

How do you randomize a number in Visual Basic?

Example. This example uses the Rnd function to generate a random integer value from 1 to 6. Dim MyValue As Integer MyValue = Int((6 * Rnd) + 1) ' Generate random value between 1 and 6.


1 Answers

Check out the Fisher-Yates shuffle algorithm here: http://en.wikipedia.org/wiki/Knuth_shuffle

with a more concise discussion by this site's chief overlord here: http://www.codinghorror.com/blog/archives/001015.html

There is a simple C# implementation in the blog entry that should be real easy to change to VB.NET

like image 81
nick Avatar answered Sep 30 '22 13:09

nick