Public Class RandomCharacters
Private ReadOnly m_allowedCharacters() As Char
Private m_remainingCharacters As Integer
Private ReadOnly m_random As System.Random
Public Sub New(ByVal allowedCharacters As String, ByRef random As System.Random)
m_allowedCharacters = allowedCharacters.ToCharArray
m_remainingCharacters = m_allowedCharacters.Length
m_random = random
End Sub
Public ReadOnly Property CharactersRemaining As Boolean
Get
Return m_remainingCharacters > 0
End Get
End Property
Public Function GetNextCharacter() As Char
If m_remainingCharacters < 1 Then
Throw New InvalidOperationException("Cannot retrieve more characters from source")
End If
' We are considering the characters in the range 0 -> # remaining characters
' Get a random element from within that range and store a copy of it to return
' at the end of this iteration
Dim nextCharacterIndex As Integer = m_random.Next(m_remainingCharacters)
Dim returnCharacter As Char = m_allowedCharacters(nextCharacterIndex)
' Place the last character from the range we are considering
' (will not be considered next time) into the place where we
' just got the character from.
m_allowedCharacters(nextCharacterIndex) = m_allowedCharacters(m_remainingCharacters - 1)
' And now decrement the range that we will consider for the
' next iteration
m_remainingCharacters = m_remainingCharacters - 1
Return returnCharacter
End Function
End Class