|
|
|
At times you may need to process elements of an array, a collection, or a dictionary object in random order, for example when sampling a population or (more often) when writing a game, such as a card game. Here's a class that you can use in a For Each statement to randomly process all the elements of any data structure that implements the IEnumerable interface: |
Click here to copy the following block | Class RandomIterator Implements IEnumerable
Dim items As New ArrayList()
Sub New(ByVal collection As IEnumerable, ByVal seed As Integer) Dim rand As New Random(seed) Dim o As Object For Each o In collection Items.Insert(Rand.Next(0, Items.Count + 1), o) Next End Sub
Public Function GetEnumerator() As System.Collections.IEnumerator _ Implements System.Collections.IEnumerable.GetEnumerator Return items.GetEnumerator() End Function End Class |
This code shows how you can use the RandomIterator class to randomly process all the elements in a string array, but you can use it with collection and dictionaries alike: |
This code produces the following sequence: three five two four one
|
|
|
|
Submitted By :
Nayan Patel
(Member Since : 5/26/2004 12:23:06 PM)
|
|
|
Job Description :
He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting. |
View all (893) submissions by this author
(Birth Date : 7/14/1981 ) |
|
|