Solved
Recursion & Random Numbers
Posted on 2002-06-08
Okay, here's a fun question for the technically minded. It's been a while since I've done anything even close to recursion, and I can't find my uni notes.
I've got a Random Number generator which I want to check if numbers have been called already - I guess kind of like a lottery in some ways.
Now I've got my function:
Public Function RandomNum(iLow As Integer, iHigh As Integer) As Integer
Dim a As Integer
Randomize
a = Int(Rnd * (iHigh - iLow)) + iLow
If Not Already_Called(a) Then
RandomNum = a
Else
RandomNum = RandomNum(iLow, iHigh)
End If
End Function
Now, the calling line is storing the return number to an array which the Already_Called function checks to see if the number has been called previously and returns true if the number is already found in the number array and false if it isn't. However, upon Already_Called returning True, my RandomNum function generates an "Out of Stack Space" error message when getting nearer the end of the array when only a finite amount of numbers are left.
Can anyone see anything that I have obviously wrong? I know that a recursive function needs a close or collapse, which I have, if it's not already generated the number, it returns a, otherwise it keeps calling itself until it generates a number it hasn't already called before.
I guess the problem may be caused by the fact that it is feasible that the random number generator could be generating with an iLow of 1 and an iHigh of 10 and upon reaching the last number never calls the only missing number. Is there an obvious solution for this other than telling it to go and figure out what the last number that hasn't been called is and just calling that (which in my meagre opinion is a bit of a lame workaround).
Thanks for any help anyone can give me.