Post by RICKI have a string of of characters that are being stored in a variable. I
would like to randomize those characters. How can I do that?
Rick
Split the string into an array of characters and shuffle the array:
Option Explicit
WScript.Quit testShuffleString()
''= tests string shuffle (shuffleArray(), str2CharArr())
' ============================================================================
Function testShuffleString()
Dim aSeeds : aSeeds = Array( _
"ABCDE", "", "AABBCC", "rambomize", "11111511111" _
)
Dim sSeed
For Each sSeed In aSeeds
WScript.Echo "--- |" & sSeed & "|"
Dim nIdx
For nIdx = 0 To 1 + Len( sSeed )
' WScript.Echo " |" & shuffleS( sSeed ) & "|"
WScript.Echo " |" & Join( shuffleArray( str2CharArr( sSeed ) ), "" ) & "|"
Next
WScript.Echo
Next
testShuffleString = 0
End Function
''= shuffles one dimensional array
' ============================================================================
Function shuffleArray( ByVal a1D )
Dim nTo : nTo = UBound( a1D ) + 1
Dim nIdx, nPos, vTmp
For nIdx = 0 To UBound( a1D )
nPos = IRandR( nIdx, nTo )
vTmp = a1D( nIdx )
a1D( nIdx ) = a1D( nPos )
a1D( nPos ) = vTmp
Next
shuffleArray = a1D
End Function
''= splits string into array of chars
' ============================================================================
Function str2CharArr( sTxt )
ReDim aChars( Len( sTxt ) - 1 )
Dim nPos
For nPos = 0 To UBound( aChars )
aChars( nPos ) = Mid( sTxt, nPos + 1, 1 )
Next
str2CharArr = aChars
End Function
''= generates 'random' integer between nFrom and (nTo - 1)
' ============================================================================
Function IRandR( ByVal nFrom, ByVal nTo )
IRandR = nFrom + Int( Rnd * (nTo - nFrom) )
End Function