Click here to Skip to main content
15,886,093 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Vb.Net: how to generate random nuber, not including previos generaded???
Posted

The only way to do that is to either :
1) Keep track of the values you have previously used and generate another if you find a random value in the list
Or
2) Set up a List of all possible values and generate an index randomly. Set the value at that index to be the random number and remove it from the list.

They both have advantages and disadvantages:

The first method can be extremely slow as the number of "used" values increases - because there is more chance each time of generating a new random number that has been used. In extreme cases, it may never find an unused value.
The second method can be very inefficient in memory terms if you have a wide range of numbers. For limited ranges however, it is a lot more deterministic than the other method.
 
Share this answer
 
I made a Bingo game and use a randomly generated set of 75 ball numbers for each new game.

The array is public and is aryRnd(75). This works well for me and is reasonably fast.

You can then use the array as needed in the project.

VB
Dim valueRnd As String = ""
Dim ballCnt As Single = 0
Dim gotcha As Boolean = False
Dim z As Single = 0
Dim Xy As Single

For Xy = 0 To 75    'Function BallList
    aryRnd(Xy) = 0
Next (Xy)

Do While ballCnt <= 74
    gotcha = False

    ' Initialize the random-number generator.
    Randomize()

    '      Generate random value between 1 and 75.
    valueRnd = CInt(Int((75 * Rnd()) + 1))

    '    Check for existence of the number in the array
    For Xy = 1 To ballCnt + 1
        If aryRnd(Xy) = valueRnd Then
            gotcha = True
            Exit For
        End If
    Next Xy

    '   Add to array if not found
    If Not gotcha Then
        aryRnd(ballCnt + 1) = valueRnd
        ballCnt = ballCnt + 1
    End If
Loop
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900