mardi 31 octobre 2017

How to change value of item in list

How do I change a value that is stored in a list. I'm making a program with weighted numbers. the program will pick a weighted number and add it to the picked numbers variable. it will do this twice. i wanted so that when a number if picked and the sum of both of the numbers is greater than the last sum then the weight for the numbers that were picked will go up making them more likely to be picked again. comment if you need a better explanation. this is the code i'm using just now.

Public Class Form1

    Structure Weighted
        Dim Number As Integer
        Dim Weight As Integer
    End Structure

    Dim Numbers As New List(Of Weighted)
    Dim CurrentNumber As Weighted
    Dim random As New Random
    Dim picked(1) As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        For i = 1 To 10
            CurrentNumber.Number = i
            CurrentNumber.Weight = 1

            Numbers.Add(CurrentNumber)
            ListBox1.Items.Add(CurrentNumber.Number & vbTab & ":" & vbTab & CurrentNumber.Weight)
        Next

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim SumOfWeight As Integer
        Dim RandomNumberPicked As Integer

        For i = 0 To 1
            SumOfWeight = 0
            For Each item In Numbers
                SumOfWeight += item.Weight
            Next
            RandomNumberPicked = random.Next(0, SumOfWeight + 1)
            For Each item In Numbers
                If RandomNumberPicked < item.Weight Then
                    picked(i) = item.Number
                    Numbers(picked(i) - 1).Weight += 1 ''error occures here
                    Exit For
                Else
                    RandomNumberPicked -= item.Weight
                End If
            Next
        Next

        MsgBox(picked(0) & " + " & picked(1) & " = " & picked(0) + picked(1))

        ListBox1.Items.Clear()
        For Each item In Numbers
            ListBox1.Items.Add(item.Number & vbTab & ":" & vbTab & item.Weight)
        Next

    End Sub
End Class

Error Message




Aucun commentaire:

Enregistrer un commentaire