I have a function that generates a random 6-Digit Number, so there should be at least 6^10 possible combinations. However I ran the function 1000 times and I got the same numbers 3 or 4 times. Here is my code:
VB Code:
<%
Function RandomPW()
For X = 1 To 6
Randomize
strPW = strPW & CHR(Int((9 * Rnd) + 48))
Next
RandomPW = strPW
End Function
for i = 0 to 1000
response.write RandomPW() & "<br>"
next
%>
After I got the result, I put it into Excel and sorted it. Attached is the list that I was returned, after I sorted it in Excel.
Am I doing something wrong as far as generating random numbers?
thanks,
Dimava
NXSupport - Your one-stop source for computer help
In this line check the 9 it is constant try make it variable
strPW = strPW & CHR(Int((9 * Rnd) + 48))
try this
strPW = strPW & CHR(Int((x * Rnd) + 48))
You should not be calling Randomize repeatedly, once is enough - and will make the data appear to be more 'random', as each value will be based on the previous value rather than being completely new.
Also, as you are only allowing 9 possible values in 6 characters, repetition is going to be more frequent than if you had a larger range of values (such as 26 values in 10 chars).
Is there i way of generating a random number and them not generating this number again? So say i wanted to generate 10 random numbers between 1 and 100 how do i stop it repeated the same number twice?
To do that there are two main options, as the amount of possible values (100) and the amount to be selected (10) are both so small, either method should be ok. Note that unless the amount of possible values is large the second method is likely to be more efficient in most cases.
1) Create the random numbers and store them in an array, when you create a new one check that it hasn't been used before; if it has, generate another number. eg:
VB Code:
Dim aNumbers(9) As Integer
Dim iCount As Integer
Dim iRnd As Integer
Dim iCheck As Integer
Dim bIsValid As Boolean
For iCount = 0 To 9
Do
'pick the random number
iRnd = Int((Rnd(1) * 100) + 1)
'see if it has been used before
bIsValid = True
For iCheck = 0 To (iCount - 1)
If aNumbers(iCheck) = iRnd Then
'it has - so try again
bIsValid = False
Exit For
End If
Next iCheck
Loop Until bIsValid = True
'this number is unused, so use it
aNumbers(iCount) = iRnd
Next iCount
2) Don't actually use random numbers, you create a list (array or collection) of the valid numbers, and pick from random positions (removing items as they are used).
VB Code:
'set up list of valid numbers
Dim cNumbers As Collection
Dim iCount As Integer
Set cNumbers = New Collection
For iCount = 1 To 100
cNumbers.Add iCount
Next iCount
Dim aNumbers(9) As Integer
Dim iRndPos As Integer
For iCount = 0 To 9
'pick the random position
iRndPos = (Rnd(1) * cNumbers.Count) + 1
'get the item from that position (our "random" number)