Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

Weighted Randomizer (Source)


balliztik1
 Share

Recommended Posts

There are many situations where you need to randomize a value, and weight the chances. For instance, a chest would do this. Instead of having to construct a list of conditionals for each occurrence, you could have a function automate this for you. This function is my WeightedRandomizer function.

```
Function WeightedRandomizer(ByRef NumberList() As Long) As Byte
    Dim Total As Double, current As Byte, Chance As Double

    For current = 0 To UBound(NumberList)
        Total = Total + NumberList(current)
    Next

    Randomize
    Chance = Int(Total * Rnd) + 1

    For current = 0 To UBound(NumberList)
        If NumberList(current) >= Chance Then
            WeightedRandomizer = current
            Exit Function
        Else
            Chance = Chance - NumberList(current)
        End If
    Next
End Function
```

Usage is fairly easy. You simply supply the function with an array of Longs (up to 255, though you can alter it). The function then adds all the values together to get a maximum value, then randomizes a number between 1 and that number. Whichever index it refers to is returned. Here's the chest example from above:

```
Dim chances(1) as Long, items(1) as Long
Items(0) = 23      'Sword item number
Chance(0) = 35  '35 total chances to get the sword
Items(1) = 24      'Axe item number
Chance(1) = 20    '20 total chances to get the axe

Call GiveItem(index, Items(WeightedRandomizer(Chance)), 1000) 'Give that item with 1000 durability
```

Now, instead of many if-statements to determine the index of the item to give, it's just a simple function. This can be used for just about anything, as long as you supply an array. You can change the data types freely.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...