Classic ASP - Unique Random Numbers

Classic ASP - Unique Random Numbers

Many of you will know that I do like coding and out of all the languages I like Microsoft Classic ASP. The reason is simple, I started coding in the 1980s with BBC Basic on my Acorn Electron then GW and Visual Basic on PCs and then a natural progression to Classic ASP when the web came along. It's such a simple language to master and easy to follow. You can take basic HTML files and add dynamic content using the simple <% %> directives.

From time to time you need functions which extend the language and the other day working on I needed to fill an array with 5 unique numbers from a specific range. Here is the result with example code following on.



Function RandomUnique(min, max, n)

    ' Returns a string of comma delimited numbers of unique values within a specific range
    ' min & max are the upper and lower 
    ' n is the number of values to return in the string
    ' x = RandomUnique(1, 59, 6)
    ' arrLotteryNumbers = Split( x, "," )
    If min > max Then
        RandomUnique = "min > max"
        Exit Function 
    End If
    If n > (max - min) + 1 Then
        RandomUnique = "Too many numbers requested in the range."
        Exit Function
    End If
    result = ","
    cnt1 = n
    Do Until cnt1 = 0
        RndNumber = Int((max - min + 1) * rnd + min)
        If (InStr(1, result, "," & RndNumber & "," ) = 0) Then
            result = result & RndNumber & ","
            cnt1 = cnt1 - 1
        End If
    result = Left(result, Len(result)-1)
    result = Right(result, Len(result)-1)
    RandomUnique = result
End Function



Go back to the previous page