我有一个类型列表System.IO.FileInfo
,我想随机列表.我以为我记得看到过list.randomize()
一会儿的东西,但我找不到我可能已经看到的地方.
我第一次尝试这个功能让我有了这个功能:
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
我发送它想要它迭代到的最大值,并且我想要随机化内容的列表的引用.该变量IMG_COUNT
在脚本中设置得更远,指定我想要显示多少随机图像.
谢谢你们,我很感激:D
查看Fisher-Yates shuffle算法:http://en.wikipedia.org/wiki/Knuth_shuffle
这个网站的主要负责人在这里进行了更为简洁的讨论:http: //www.codinghorror.com/blog/archives/001015.html
博客条目中有一个简单的C#实现,应该很容易更改为VB.NET
我List
使用以下Randomize()
函数扩展了类以使用Fisher-Yates shuffle算法:
'''''' Randomizes the contents of the list using Fisher–Yates shuffle (a.k.a. Knuth shuffle). ''' '''''' ''' Randomized result '''Function Randomize(Of T)(ByVal list As List(Of T)) As List(Of T) Dim rand As New Random() Dim temp As T Dim indexRand As Integer Dim indexLast As Integer = list.Count - 1 For index As Integer = 0 To indexLast indexRand = rand.Next(index, indexLast) temp = list(indexRand) list(indexRand) = list(index) list(index) = temp Next index Return list End Function