0

I have an array filled with objects, each object has an attribute named amount. I want to subtract a given number evenly from random objects based on the amount.

I'll better explain it on the following example:

        Dim subtractBy as integer = 5 'means i want to substract a total of 5
        Dim Generator As System.Random = New System.Random()

        While (subtractBy > 0)
                Dim randomItem = array2(Generator.Next(0, array2.Count))

                If (randomItem.amount > 0 )  Then
                    randomItem.changeAmountBy(-1)
                    subtractBy = subtractBy - 1
                End If

        End While

The problem with that example is, every object has the same chance to be choosen for substraction. I want that every object gets higher chances linear to the amount atribute. So an object with amount=6 has 6x higher chance to be selected than the object with amount=1 and so on.

(Althought the example is in VB, I appreciate also general non-code answers)

Thank you

Labe
  • 117
  • 1
  • 6
  • 3
    See http://stackoverflow.com/questions/1761626/weighted-random-numbers – Hans Z Apr 21 '14 at 16:45
  • 1
    To summarize that last post, add up all the amounts as your total, put all your objects in a list. Find a random number between 0 and total, iterate through the list, subtracting amount from total every time, when you get < 1, return the object you're on. – Hans Z Apr 21 '14 at 16:47
  • @HansZ Thank you, I didn't think it could be as easy as this. – Labe Apr 21 '14 at 16:50

0 Answers0