Forum Moderators: open

Message Too Old, No Replies

Random Numbers

Why is this so difficult

         

wingnut101

4:17 am on Nov 8, 2006 (gmt 0)

10+ Year Member



Does anybody know how to generate a truly random bit of code using asp? I am using the following script, but the codes it returns are definitely not random. There should be a few million possibilities for a 5 character code, but it seems that it's returning the same code every 20th time or so.

codecharacters = 35

Array("a","b","c","d","e","f","g","h","i","j","k","l", _
"m","n","o","p","q","r","s","t","u","v","w","x", _
"y","z","1","2","3","4","5","6","7","8","9")

FOR x = 1 TO 5
RANDOMIZE()
thiscode = (Int(((codecharacters - 1) * Rnd) + 1))

mattglet

12:41 pm on Nov 8, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Here you go:

function RandomString(intLength)
Randomize()
dim strPattern, intDiff, i, strReturn

strPattern = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"

intDiff = len(strPattern) - 1

for i = 1 to intLength
strReturn = strReturn & Mid(strPattern, Round((rnd()*intDiff)+1),1)
next

RandomString = strReturn
end function

mrMister

3:32 am on Nov 20, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



"truly random" isn't possible with a computer. If you're doing anything important with computer-generated pseudo-random numbers you need to be very careful.

For non-critical purposes, mattglett's code will work well, but call Randomize() only once per script (not inside the function as mattglett has done) otherwise the random numbers will become easily predectable (especially on fast/repetitive calls to the function).

[edited by: mrMister at 3:33 am (utc) on Nov. 20, 2006]

brickwall

10:55 am on Dec 7, 2006 (gmt 0)

10+ Year Member



... but call Randomize() only once per script (not inside the function as mattglett has done) otherwise the random numbers will become easily predectable ...

agreed.

placing Randomize() inside procedures (esp looping procedures) will produce a lot of duplicates. Structure your generator in such a way that Randomize() is only called once per page load.