Discussion:
How to Randomize characters in a string
(too old to reply)
RICK
2008-08-19 14:28:04 UTC
Permalink
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?

Rick
Pegasus (MVP)
2008-08-19 14:37:17 UTC
Permalink
Post by RICK
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?
Rick
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.
RICK
2008-08-19 14:52:05 UTC
Permalink
But, my characters are alphanumeric.

What I have done is to create seven random letters followed by one random
number and one random special character.

I now want to randomize these nine characters into another
Post by Pegasus (MVP)
Post by RICK
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?
Rick
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.
Pegasus (MVP)
2008-08-19 15:06:04 UTC
Permalink
Let's assume your have name="Rick". Using my method, you generate
an array containing four randomised numbers, e.g.
arr(1) = 4
arr(2) = 1
arr(3) = 3
arr(4) = 2
Your randomised string will now be
mid(name, arr(1), 1) & mid(name(arr(2), 1) & mid(name, arr(3), 1) &
mid(name(arr(4), 1)

You must, of course, automate the process instead of writing it
out as above.
Post by RICK
But, my characters are alphanumeric.
What I have done is to create seven random letters followed by one random
number and one random special character.
I now want to randomize these nine characters into another
Post by Pegasus (MVP)
Post by RICK
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?
Rick
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.
Anthony Jones
2008-08-19 15:43:05 UTC
Permalink
Post by RICK
But, my characters are alphanumeric.
What I have done is to create seven random letters followed by one random
number and one random special character.
I now want to randomize these nine characters into another
What is meant by randomize in that last sentence? Do you actually mean
arrange the characters into another random order?

Since the letters are choosen at random any way all you actually need is it
choose two random numbers that indicate the ordinal position of the number
and the special character.

What structure are the characters currently held in, a string or as elements
of an array?
--
Anthony Jones - MVP ASP/ASP.NET
RICK
2008-08-19 16:16:03 UTC
Permalink
Actually what I want to do is to shuffle the characters. Any thoughts?
Post by Anthony Jones
Post by RICK
But, my characters are alphanumeric.
What I have done is to create seven random letters followed by one random
number and one random special character.
I now want to randomize these nine characters into another
What is meant by randomize in that last sentence? Do you actually mean
arrange the characters into another random order?
Since the letters are choosen at random any way all you actually need is it
choose two random numbers that indicate the ordinal position of the number
and the special character.
What structure are the characters currently held in, a string or as elements
of an array?
--
Anthony Jones - MVP ASP/ASP.NET
Anthony Jones
2008-08-21 08:15:12 UTC
Permalink
Post by RICK
Actually what I want to do is to shuffle the characters. Any thoughts?
Since the characters are already random what purpose is served by shuffling
them about?
So far is seems sufficient just to move the last two characters about.
--
Anthony Jones - MVP ASP/ASP.NET
RICK
2008-08-19 16:20:15 UTC
Permalink
And to answer your second question the characters are stored in a named string.
Post by Anthony Jones
Post by RICK
But, my characters are alphanumeric.
What I have done is to create seven random letters followed by one random
number and one random special character.
I now want to randomize these nine characters into another
What is meant by randomize in that last sentence? Do you actually mean
arrange the characters into another random order?
Since the letters are choosen at random any way all you actually need is it
choose two random numbers that indicate the ordinal position of the number
and the special character.
What structure are the characters currently held in, a string or as elements
of an array?
--
Anthony Jones - MVP ASP/ASP.NET
axtens
2008-08-19 15:51:55 UTC
Permalink
Post by RICK
But, my characters are alphanumeric.
What I have done is to create seven random letters followed by one random
number and one random special character.
I now want to randomize these nine characters into another
Rick,

I hope the code is fairly self-explanatory. Basically, it finds random
numbers between 1 and 9, removing them from pattern (the acceptable
choices) until pattern is empty, and appends those found to selection.
Then it iterates through selection, using the numbers therein as
offsets into original.

Kind regards,
Bruce.



dim a
dim n
dim original
dim pattern
dim selection
dim final
dim i

randomize timer

original = "abcdefg1@"
pattern = "123456789"
selection = ""
final = ""

' pick 9 random numbers without duplicates
do
n = int( rnd * 9 ) + 1

i = instr(pattern, cstr(n))
if i > 0 then
pattern = left(pattern,i-1) & mid(pattern,i+1)
selection = selection & cstr(n)
end if
if len(pattern) = 0 then exit do
loop

'use those numbers to select items from the original
for i = 1 to len(selection)
n = mid(selection,i,1)
final = final & mid(original,n,1)
next

wscript.echo original, selection, final

---
Sample run:

abcdefg1@ 329675841 ***@fge1da
RICK
2008-08-19 18:37:00 UTC
Permalink
Thanks. Worked great.
Post by axtens
Post by RICK
But, my characters are alphanumeric.
What I have done is to create seven random letters followed by one random
number and one random special character.
I now want to randomize these nine characters into another
Rick,
I hope the code is fairly self-explanatory. Basically, it finds random
numbers between 1 and 9, removing them from pattern (the acceptable
choices) until pattern is empty, and appends those found to selection.
Then it iterates through selection, using the numbers therein as
offsets into original.
Kind regards,
Bruce.
dim a
dim n
dim original
dim pattern
dim selection
dim final
dim i
randomize timer
pattern = "123456789"
selection = ""
final = ""
' pick 9 random numbers without duplicates
do
n = int( rnd * 9 ) + 1
i = instr(pattern, cstr(n))
if i > 0 then
pattern = left(pattern,i-1) & mid(pattern,i+1)
selection = selection & cstr(n)
end if
if len(pattern) = 0 then exit do
loop
'use those numbers to select items from the original
for i = 1 to len(selection)
n = mid(selection,i,1)
final = final & mid(original,n,1)
next
wscript.echo original, selection, final
---
Dr J R Stockton
2008-08-20 16:15:54 UTC
Permalink
In microsoft.public.scripting.vbscript message <571A454D-2051-46AF-
Post by RICK
Thanks. Worked great.
Post by axtens
' pick 9 random numbers without duplicates
do
n = int( rnd * 9 ) + 1
i = instr(pattern, cstr(n))
if i > 0 then
pattern = left(pattern,i-1) & mid(pattern,i+1)
selection = selection & cstr(n)
end if
if len(pattern) = 0 then exit do
loop
That seems inefficient, though, since apparently (for example) for the
9th number it must keep testing until it finds the right one. For nine
or fewer numbers (starting with 1), however, such inefficiency will not
actually make much difference. OTOH, for more numbers ISTM that the
reject-unwanted will need to be recoded, since, by rejecting both
genuine and spurious duplicates, it will not give a uniformly equi-
probable result (and the inefficiency will increase).

If it is necessary to generate a list of integers in a random order (not
needed for this job) then a simple modification of the efficient shuffle
will give an efficient deal, as shown on the cited site.
--
(c) John Stockton, nr London UK. ?@merlyn.demon.co.uk IE7 FF2 Op9 Sf3
news:comp.lang.javascript FAQ <URL:http://www.jibbering.com/faq/index.html>.
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
axtens
2008-08-21 05:00:24 UTC
Permalink
Post by Dr J R Stockton
That seems inefficient
Granted. However, in this situation, the "monte carlo" (if that's the
correct label) approach works, and the original poster is happy with
it.
That's being perhaps a little too pragmatic, but it seemed to me at
the
time that a shuffle was a bit like killing a mosquito with a howitzer.

Kind regards,
Bruce.
--
Bruce M. Axtens
Software Engineer
The Protium Project
http://www.protiumblue.com
http://codeaholic.blogspot.com
Dr J R Stockton
2008-08-21 15:33:11 UTC
Permalink
In microsoft.public.scripting.vbscript message <cd59c3e3-4e47-45a0-8fcb-
Post by axtens
Post by Dr J R Stockton
That seems inefficient
Granted. However, in this situation, the "monte carlo" (if that's the
correct label) approach works, and the original poster is happy with
it.
True, but this is News and not E-mail. When writing, one should
consider also that other people may see the code and use it in
circumstances where such error could matter.

For a discussion of the method, see <http://en.wikipedia.org/wiki/Knuth_
shuffle>.
--
(c) John Stockton, near London. *@merlyn.demon.co.uk/?.?***@physics.org
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)
Dr J R Stockton
2008-08-19 18:19:41 UTC
Permalink
In microsoft.public.scripting.vbscript message <#***@TK2MSFT
NGP05.phx.gbl>, Tue, 19 Aug 2008 16:37:17, "Pegasus (MVP)"
Post by Pegasus (MVP)
Post by RICK
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?
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/?.?***@physics.org
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)
ekkehard.horner
2008-08-19 15:29:23 UTC
Permalink
Post by RICK
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?
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
Old Pedant
2008-08-20 00:42:01 UTC
Permalink
Post by RICK
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?
Man, do peole like to make this complex!

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!

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

foo = ShuffleString( "ALLIGATOR" )

***********

Obviously, if you can create the original string in the array, you can
bypass the copy from string to array.
Dr J R Stockton
2008-08-20 18:41:55 UTC
Permalink
In microsoft.public.scripting.vbscript message <E80766BD-B20E-4F81-9D51-
Post by Old Pedant
Post by RICK
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,
Randomize ' only do this once per file!
only once per program execution.
Post by Old Pedant
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)
Old Pedant
2008-08-21 20:49:01 UTC
Permalink
Post by Dr J R Stockton
Post by Old Pedant
Randomize ' only do this once per file!
only once per program execution.
Yes, of course.

Should have said "once per file, at global scope level" which is then the
same thing. Newbies may hae trouble figuring out whether it does occur one
per program execution or not, so I think it's clearer to say "once per file"
if you properly qualify it.

*********
Post by Dr J R Stockton
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.
... etc. ...
Yes. But qute frankly, who cares? It's good enough for practical purposes.

Don't get me wrong, I enjoy your theoretical approach, but for the typical
ASP page and the typical ASP newbie, I think short and sweet is better.
Besides, what is the likelihood that a newbie would understand your
"translate from Pascal, assuming the string has been split into an array 1..N
of characters..."? I probably wouldn't have bothered to chime in if you had
given him a real solution written in VBScript. [And I'm pretty sure I'm
right about his being a newbie, given his question and his responses.]

It's kind of fun to find two people frequenting this list who are more
pedantic than I am. Makes me want to try harder. Still, I think giving
practical answers to newbies is more important.
Dr J R Stockton
2008-08-22 16:22:09 UTC
Permalink
In microsoft.public.scripting.vbscript message <4B4F2F74-D8AB-4170-8C38-
Post by Old Pedant
Post by Dr J R Stockton
Post by Old Pedant
Randomize ' only do this once per file!
only once per program execution.
Yes, of course.
Should have said "once per file, at global scope level" which is then the
same thing. Newbies may hae trouble figuring out whether it does occur one
per program execution or not, so I think it's clearer to say "once per file"
if you properly qualify it.
*********
Post by Dr J R Stockton
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.
... etc. ...
Yes. But qute frankly, who cares? It's good enough for practical purposes.
Those who publish solution should take reasonable care to publish sound
ones, especially where that does not add complexity to the code. The
proper way to shuffle is reasonably well known.
Post by Old Pedant
Don't get me wrong, I enjoy your theoretical approach, but for the typical
ASP page and the typical ASP newbie, I think short and sweet is better.
Besides, what is the likelihood that a newbie would understand your
"translate from Pascal, assuming the string has been split into an array 1..N
of characters..."?
That's an exercise for people like you ... However, anyone should be
able to see from
for J := Max downto 2 do Swap(A[J], A[1+Random(J)]) ;
that there is a count from J down to 2, that there is on each occasion a
swap, and that Random is called with a varying argument.

And if the OP had followed the URLs that I gave, he'd have found more
explanation, even then. Now, <URL:http://www.merlyn.demon.co.uk/vb-
maths.htm> contains a shuffle routine and a test for it, to be improved
before long?. The core is :

For K = 2 to L : J = L-K+1
X = Random(J) : T = A(X) : A(X) = A(J) : A(J) = T '' Swap A(X) A(J)
--
(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)
Dr J R Stockton
2008-08-22 18:10:37 UTC
Permalink
  For K = 2 to L : J = L-K+1
    X = Random(J) : T = A(X) : A(X) = A(J) : A(J) = T '' Swap A(X) A(J)
There's a bug somewhere in the test page ... not necessarily in that
part ...

--
(c) John Stockton, near London, UK. Posting with Google.
Mail: J.R.""""""""@physics.org or (better) via Home Page at
Web: <URL:http://www.merlyn.demon.co.uk/>
FAQish topics, acronyms, links, etc.; Date, Delphi, JavaScript, ...
Dr J R Stockton
2008-08-22 18:46:21 UTC
Permalink
Post by Dr J R Stockton
  For K = 2 to L : J = L-K+1
    X = Random(J) : T = A(X) : A(X) = A(J) : A(J) = T '' Swap A(X) A(J)
There's a bug somewhere in the test page ... not necessarily in that
part ...
Should be

For K = 1 to L : J = L-K
X = Random(J+1) : T = A(X) : A(X) = A(J) : A(J) = T '' Swap A(X)
A(J)

--
  (c) John Stockton, near London, UK.  Posting with Google.
 Mail: J.R.""""""""@physics.org or (better) via Home Page at
 Web:  <URL:http://www.merlyn.demon.co.uk/>
 FAQish topics, acronyms, links, etc.; Date, Delphi, JavaScript, ...
d***@gmail.com
2017-01-03 12:46:04 UTC
Permalink
Post by Old Pedant
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,
Randomize ' only do this once per file!
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
foo = ShuffleString( "ALLIGATOR" )
Thank you Old Pedant!
Your code works great for my strings
Mayayana
2017-01-03 14:01:16 UTC
Permalink
<***@gmail.com> wrote

I don't see the original post. I'm guessing it's
coming out of Google Groups. You might consider
using a real newsreader and a real usenet server,
so that you can use the real usenet newsgroups.

In any case, Randomize should be called with
every call to Shuffle. Randomize without a parameter
calls Timer to get a seed number for shuffling. You can
also use a unique numeric parameter if you like. Without
calling Randomize you'll get the same seed each time.
So calling Randomize only once for each file is exactly
what you don't want to do because you'll get the same
shuffle each time.
Auric__
2017-01-03 17:54:06 UTC
Permalink
Post by Mayayana
I don't see the original post. I'm guessing it's
coming out of Google Groups. You might consider
using a real newsreader and a real usenet server,
so that you can use the real usenet newsgroups.
"Doug" is a Google Groupie. The thread is from 2008, with several replies by
old regs Pegasus, ekkehard.horner, Anthony Jones, axtens, and Dr J R
Stockton. See here if you're interested (watch the wordwrap):

https://groups.google.com/forum/#!
topic/microsoft.public.scripting.vbscript/b34hZ4TYjsk
Post by Mayayana
In any case, Randomize should be called with
every call to Shuffle. Randomize without a parameter
calls Timer to get a seed number for shuffling. You can
also use a unique numeric parameter if you like. Without
calling Randomize you'll get the same seed each time.
So calling Randomize only once for each file is exactly
what you don't want to do because you'll get the same
shuffle each time.
Randomize only needs to be called once per run. Calling it every time you
enter a function is just a waste of cpu cycles.
--
The giver and the recipient may each define a "reward" quite differently.
Mayayana
2017-01-04 00:38:37 UTC
Permalink
"Auric__" <***@email.address> wrote

| "Doug" is a Google Groupie. The thread is from 2008

Ah. I didn't notice the date.

| Randomize only needs to be called once per run. Calling it every time you
| enter a function is just a waste of cpu cycles.
|

He said once per file. Once per run is what I'm
suggesting. In other words, if you randomize the
same string 3 times without calling Randomize then
the result will be 3 matching shuffles. So the best
approach is to call it with every Shuffle call, which
is hardly a waste of CPU cycles. It just retrieves
the system time. .... But maybe we're saying the same
thing. I'm not sure.
Evertjan.
2017-01-03 16:48:23 UTC
Permalink
Post by d***@gmail.com
Post by Old Pedant
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
Randomize ' only do this once per file!
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
foo = ShuffleString( "ALLIGATOR" )
Thank you Old Pedant!
Your code works great for my strings
No need for arrays:

function ShuffleString(text)
randomize()
ln = len(text)
for i=1 to ln
r = int( rnd() * ln ) + 1
text = swapLr(text,i,r)
next
ShuffleString = text
end function

function swapLr(tx,i,r)
tempi = mid(tx,i,1)
tempr = mid(tx,r,1)
tx = replLr(tx,r,tempi)
tx = replLr(tx,i,tempr)
swapLr = tx
end function

function replLr(tx,beg,letter)
Set myRegExp = New RegExp
myRegExp.Pattern = "^(.{" & beg-1 & "})."
replLr = myRegExp.replace(tx,"$1"&letter)
end function

response.write ShuffleString( "ALLIGATOR" )
--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Dr J R Stockton
2017-01-05 19:23:44 UTC
Permalink
Post by Evertjan.
Post by d***@gmail.com
Post by Old Pedant
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
Randomize ' only do this once per file!
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
foo = ShuffleString( "ALLIGATOR" )
Thank you Old Pedant!
Your code works great for my strings
function ShuffleString(text)
randomize()
ln = len(text)
for i=1 to ln
r = int( rnd() * ln ) + 1
text = swapLr(text,i,r)
next
ShuffleString = text
end function
function swapLr(tx,i,r)
tempi = mid(tx,i,1)
tempr = mid(tx,r,1)
tx = replLr(tx,r,tempi)
tx = replLr(tx,i,tempr)
swapLr = tx
end function
function replLr(tx,beg,letter)
Set myRegExp = New RegExp
myRegExp.Pattern = "^(.{" & beg-1 & "})."
replLr = myRegExp.replace(tx,"$1"&letter)
end function
response.write ShuffleString( "ALLIGATOR" )
It might be interesting to compare the speeds of the array code and the
string code.
--
(c) John Stockton, Surrey, UK. ¬@merlyn.demon.co.uk Turnpike v6.05 MIME.
Merlyn Web Site < > - FAQish topics, acronyms, & links.
Evertjan.
2017-01-05 23:51:09 UTC
Permalink
Post by Dr J R Stockton
Post by Evertjan.
Post by d***@gmail.com
Post by Old Pedant
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
Randomize ' only do this once per file!
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
foo = ShuffleString( "ALLIGATOR" )
Thank you Old Pedant!
Your code works great for my strings
function ShuffleString(text)
randomize()
ln = len(text)
for i=1 to ln
r = int( rnd() * ln ) + 1
text = swapLr(text,i,r)
next
ShuffleString = text
end function
function swapLr(tx,i,r)
tempi = mid(tx,i,1)
tempr = mid(tx,r,1)
tx = replLr(tx,r,tempi)
tx = replLr(tx,i,tempr)
swapLr = tx
end function
function replLr(tx,beg,letter)
Set myRegExp = New RegExp
myRegExp.Pattern = "^(.{" & beg-1 & "})."
replLr = myRegExp.replace(tx,"$1"&letter)
end function
response.write ShuffleString( "ALLIGATOR" )
It might be interesting to compare the speeds of the array code and the
string code.
Be my guest.

So far it is just array-theory and string-theory.
Post by Dr J R Stockton
Post by Evertjan.
response.write ShuffleString( "ALLIGATOR" )
The clue might be here:

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Loading...