Search code examples
vbarandom

Random number between two numbers with "gaps"


I am trying to generate random numbers between two values. I am using, vba for this, so that, the way to do It would be:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

But because of the particular situation I am in, I need to exclude numbers from the middle of the sequence, so for example I need numbers between 50 and 100 and I need to exclude 80, 50, and 77, for example

So to do this, I wrap the random number generator in a Do While loop, and check if the number is one of the excluded numbers, and if it is, I keep generating numbers.

This brute-force seems to me inefficient and I am not sure about the statistical properties of the sequence if I do this,

are there more elegant algorithms to accomplish this task?

thanks in advance


Solution

  • If you had a list of valid numbers, you could use Rnd as an index into that list. In your example, the list would have 48 items. I use the number of items as the seed for Rnd:

    Option Explicit
    
    Private nums As Collection
    
    Private Sub Form_Load()
       'build your list however you need
       Set nums = BuildList(50, 100, 50, 77, 80)
    End Sub
    
    Private Sub Command1_Click()
       Dim i As Integer
       
       i = Int((nums.Count * Rnd) + 1)
       Debug.Print nums(i)
    End Sub