balliztik1 Posted December 12, 2009 Author Share Posted December 12, 2009 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 NextEnd 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 LongItems(0) = 23 'Sword item numberChance(0) = 35 '35 total chances to get the swordItems(1) = 24 'Axe item numberChance(1) = 20 '20 total chances to get the axeCall 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 More sharing options...
unknown Posted December 12, 2009 Share Posted December 12, 2009 Very nice, looks like it can save a lot of writing. Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now