View Single Post
Old 08-19-2008   #10 (permalink)
Dr J R Stockton


 
 

Re: How to Randomize characters in a string

In microsoft.public.scripting.vbscript message <#OaAWkgAJHA.2060@xxxxxx
NGP05.phx.gbl>, Tue, 19 Aug 2008 16:37:17, "Pegasus (MVP)"
<I.can@xxxxxx> posted:
Quote:

>
>"RICK" <RICK@xxxxxx> wrote in message
>news:F73BB2A2-98D0-4BBC-B3E5-2C347A597962@xxxxxx
Quote:

>>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?
Quote:

>If your string contains n characters then you could use the rnd
>function to generate n integers between 1 and n, making sure
>that each number is unique. You then use these numbers to
>rearrange the characters in your string.
I trust that you do not select algorithms professionally. Shuffling is
a standard task, for which you need only read Knuth. The efficient
method is considerably simpler.



The OP may be helped by <URL:http://www.merlyn.demon.co.uk/vb-maths.htm>
which for details cites <URL:http://www.merlyn.demon.co.uk/js-randm.htm>
and <URL:http://www.merlyn.demon.co.uk/pas-rand.htm> (I don't recall
needing Shuffle in VB before now).

function Random(N) '' Return a random integer in 0..(N-1)
Random = Int(N*Rnd)
end function

Then translate from Pascal, assuming the string has been split into an
array 1..N of characters,
for J := Max downto 2 do Swap(A[J], A[1+Random(J)]) ;
(* note : those are calls by reference,

Note that the above Pascal line executes in N(N-1)(N-2)..2 equi-probable
ways (depending on the Random results), thus providing exactly enough
randomness for the N! orders of characters in a string (assumed all
different). Then rejoin the string.

I suspect Ekkehard's code uses basically the same Shuffle algorithm.

One can of course use Mid and & to create a Swap acting directly on a
string. My feeling is that it would be slower. But, if speed matters,
test it.

--
(c) John Stockton, near London. *@merlyn.demon.co.uk/?.?.Stockton@xxxxxx
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Correct <= 4-line sig. separator as above, a line precisely "-- " (SoRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SoRFC1036)
My System SpecsSystem Spec