Re: How to Randomize characters in a string
- From: Dr J R Stockton <jrs@xxxxxxxxxxxxxxxxxx>
- Date: Wed, 20 Aug 2008 19:41:55 +0100
In microsoft.public.scripting.vbscript message <E80766BD-B20E-4F81-9D51-
8CDB55269928@xxxxxxxxxxxxx>, Tue, 19 Aug 2008 17:42:01, Old Pedant
<OldPedant@xxxxxxxxxxxxxxxxxxxxxxxxx> posted:
"RICK" wrote:
I 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?
First of all, if you don't *HAVE* to put the characters into a single
string, don't. Put them into an array. But if they are already in an array,
convert the string to an array. Example:
Randomize ' only do this once per file!
only once per program execution.
Function ShuffleString( str )
Dim temp, i, r, swap
ReDim temp( Len(str) - 1 )
For i = 0 To UBound(temp)
temp(i) = Mid(str,i+1,1)
Next
For i = 0 To UBound(temp)
r = INT( RND() * Len(str) )
swap = temp(r)
temp(r) = temp(i)
temp(i) = swap
Next
ShuffleString = Join(temp,"")
End Function
In that code, for a string of length L, RND is called L times, and
Int(RND*L) has L equally-possible values 0..L-1. Therefore, there are
L*L equi-probable sequences when the code is generated, each generating
some string.
For a string containing L distinct characters, there are factorial(L)
possible orders. For any L > 2, l^2 is not a multiple of factorial(L).
Therefore, if I have read your code correctly, it cannot generate all
possible orders with equal probability. But (assuming RND is perfect)
if the multiplier of RND varies linearly between 1 & L, as in the code I
posted earlier, there are factorial(L) possibilities each generating a
different string; so all desired output strings are possible and equi-
probable.
Donald E Knuth :-
"Random numbers should not be generated with a method chosen at random".
Me : ^ or used
--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)
.
- Follow-Ups:
- Re: How to Randomize characters in a string
- From: Old Pedant
- Re: How to Randomize characters in a string
- References:
- How to Randomize characters in a string
- From: RICK
- RE: How to Randomize characters in a string
- From: Old Pedant
- How to Randomize characters in a string
- Prev by Date: Re: Mcafee Registry Keys or other
- Next by Date: RE: Execute error: Type Mismatch: 'Execute'
- Previous by thread: RE: How to Randomize characters in a string
- Next by thread: Re: How to Randomize characters in a string
- Index(es):
Relevant Pages
|