Sam
Sam

Reputation: 500

Removing value from a List in VB

I'm making a 'Deal or No Deal' type game for a project in Visual Basic 2008.

I'm having a problem assigning the 5 values randomly to 5 boxes.

For example, in one game, the boxes could hold these values:

Box 1 = 1000 
Box 2 = 35000
Box 3 = 25000
Box 4 = 75000
Box 5 = 5000

and in another game, they could hold these values

Box 1 = 75000 
Box 2 = 25000
Box 3 = 1000
Box 4 = 5000
Box 5 = 35000

The main aim is to randomly assign these values to each box, and once a value has been assigned, it cannot be assigned to another box at the same time.

Here is the code that I have at the moment:

        Dim values As New List(Of Integer)
        Dim box(4) As Integer
        Dim randNum(4) As Integer

        'adding values to the Value list
        values.Add(1000)
        values.Add(5000)
        values.Add(25000)
        values.Add(35000)
        values.Add(75000)

        Dim i As Integer

        For i = 0 To 4
            Dim RandomClass As New Random()
            Dim RandomNumber As Integer
            RandomNumber = RandomClass.Next(0, 4)

            'assigning a box a random value form the list
            box(i) = values(RandomNumber)

            'removing that value from the list
            values.RemoveAt(i)
        Next

        Console.WriteLine("Box 1 = " & box(0))
        Console.WriteLine("Box 2 = " & box(1))
        Console.WriteLine("Box 3 = " & box(2))
        Console.WriteLine("Box 4 = " & box(3))
        Console.WriteLine("Box 5 = " & box(4))

        Console.Read()

VB keeps returning this error message when I try t run the application:

Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index

Thanks in advance for any answers.

Upvotes: 0

Views: 120

Answers (2)

Phil Preen
Phil Preen

Reputation: 638

The answer from Steve prevents the error from occurring, but I think it's still not doing quite what you want. values.RemoveAt(i) will always remove the first item from the list the first time, the second, next time, etc... it is not removing the value that you have just put in the box. To do that you should use values.RemoveAt(RandomNumber) instead.

For i = 0 To 4
    RandomNumber = RandomClass.Next(0, values.count - 1)

    'assigning a box a random value form the list
    box(i) = values(RandomNumber)

    'removing that value from the list
    values.RemoveAt(RandomNumber)
Next

Upvotes: 1

Steve
Steve

Reputation: 5545

When you remove an item, the length of the list gets smaller. So on the second loop, index of 4 no longer exists. On the third loop, 3 no longer exists and so on. Try this instead:

Dim RandomClass As New Random()
Dim RandomNumber As Integer
For i = 0 To 4
    RandomNumber = RandomClass.Next(0, values.count - 1)

    'assigning a box a random value form the list
    box(i) = values(RandomNumber)

    'removing that value from the list
    values.RemoveAt(i)
Next

Upvotes: 1

Related Questions