1,105,581 Community Members
kcasmir
Newbie Poster
5 posts since May 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]

Hi,
I want to generate an unpredictable random integer number but i dont know how. Below is my function to generate between (1 to 8)which keeps returning '6' on first run which is predicted and also, i dont want the numbers to repeat itself.

Private Function RandomIt(Hv As long, Lv As long) As long
RandomIt = Int((Hv - Lv + 1) * Rnd + Lv)
End Function

Please can someone help me out as i want to resume my work urgently.
Thank you.

Celt.Max
Newbie Poster
13 posts since Oct 2008
Reputation Points: 1 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]

Hi... if you want to get a special number on every start, try to add this line on first row of your fnc:

``Randomize Timer``

If you'd like to get unique numbers, e.g. for some series numerical, you probably have to make an array, a loop and shoud use it like this way:

``````Lv = 1
Hv = 8
Dim arrNumbers(Hv) As Boolean

'here comes some of your code where the function is used

Private Function RandomIt(Hv As Long, Lv As Long) As Long
Dim iX As Integer
Dim bExists As Boolean, bAdded As Boolean
Randomize Timer
RandomIt = Int((Hv - Lv + 1) * Rnd + Lv)
For iX = Lv To Hv
If arrNumbers(RandomIt) = True Then bExists = True: Exit For
Next iX
If bExists = False Then
arrNumbers(RandomIt) = True
End If
Loop
End Function``````

You only have to take care about the counting the function uses. If you run it more times than the space between Lv and Hv is, it will end in an infinite loop... :-) And as you know, it takes a long time to do the infinite loop. My 486 does an infinite loop in 4,86 seconds :-)

kcasmir
Newbie Poster
5 posts since May 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]

Thanks mate, you are good!

Question Answered as of 4 Years Ago by Celt.Max
You