I have this code, and it's working well. The input list is randomly shuffled very nicely.
But I'm having a little trouble understanding WHY it's working.
Specifically, what role does oBuffer
play in all of this? Why the line at the end:
oBuffer(iRandom) = oBuffer(iIndex)
I find that when I comment it out, I end up with duplicates in the output list.
I've stepped through the code, but I'm still at a loss. What exactly is going on here?
<Extension>
Public Iterator Function Randomize(Of T)(Instance As IEnumerable(Of T), Rng As Random) As IEnumerable(Of T)
Dim oBuffer As List(Of T)
Dim iRandom As Integer
Dim iIndex As Integer
Instance.ThrowIfNothing(NameOf(Instance))
Rng.ThrowIfNothing(NameOf(Rng))
oBuffer = Instance.ToList
For iIndex = 0 To oBuffer.Count - 1
iRandom = Rng.Next(iIndex, oBuffer.Count)
Yield oBuffer(iRandom)
oBuffer(iRandom) = oBuffer(iIndex)
Next
End Function
Aucun commentaire:
Enregistrer un commentaire