user2195411
user2195411

Reputation: 237

Visual Basic- random number

I have some VB code that gives me a random number, 1 between 20 (X). However, within 20 attempts, I will get the same number twice. How can I get a sequence of random numbers without any of them repeating? I basically want 1-20 to show up up in a random order if I click a button 20 times.

    Randomize()
    ' Gen random value

    value = CInt(Int((X.Count * Rnd())))

    If value = OldValue Then
        Do While value = OldValue
            value = CInt(Int((X.Count * Rnd())))    
        Loop
    End If

Upvotes: 2

Views: 5822

Answers (4)

dbasnett
dbasnett

Reputation: 11773

Add the numbers to a list and then pick them in a random order, deleting them as they are picked.

Dim prng As New Random
Dim randno As New List(Of Integer)

Private Sub Button1_Click(sender As Object, _
                          e As EventArgs) Handles Button1.Click
    If randno.Count = 0 Then
        Debug.WriteLine("new")
        randno = Enumerable.Range(1, 20).ToList 'add 1 to 20 to list
    End If
    Dim idx As Integer = prng.Next(0, randno.Count) 'pick a number
    Debug.WriteLine(randno(idx)) 'show it
    randno.RemoveAt(idx) 'remove it
End Sub

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67197

The concept is, you have to add the generated random number into a list, and before adding it into the list, make sure that the new number is not contains in it. Try this code,

        Dim xGenerator As System.Random = New System.Random()
        Dim xTemp As Integer = 0
        Dim xRndNo As New List(Of Integer)

        While Not xRndNo.Count = 20

            xTemp = xGenerator.Next(1, 21)

            If xRndNo.Contains(xTemp) Then
                Continue While
            Else
                xRndNo.Add(xTemp)
            End If

        End While

[Note: Tested with IDE]

Upvotes: 1

djv
djv

Reputation: 15774

For 1 to 20, use a data structure like a LinkedList which holds numbers 1 to 20. Choose an index from 1 to 20 at random, take the number at that index, then pop out the number in that location of the LinkedList. Each successive iteration will choose an index from 1 to 19, pop, then 1 to 18, pop, etc. until you are left with index 1 to 1 and the last item is the last random number. Sorry for no code but you should get it.

Upvotes: 1

Zeeshan
Zeeshan

Reputation: 3024

for that purpose, you need to store all previous generated number, not just one, as u did in OldValue named variable. so, store all previously generated numbers somewhere (list). and compare the newly generated number with all those in list, inside ur while loop, and keep generating numbers, while number is not equal to any of one in list..

Upvotes: 0

Related Questions