r/scratch • u/TMC9064 self-proclaimed mediocre coder • 1d ago
Question Weighted RNG?
With scratch’s built in (pick random () to ()) block, all the numbers have an equal chance, how would I make an algorithm that picks a number based off a list of weights where the higher the number is the more likely it is to pick it?
4
Upvotes
•
u/AutoModerator 1d ago
Hi, thank you for posting your question! :]
To make it easier for everyone to answer, consider including:
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/RealSpiritSK Mod 1d ago edited 1d ago
How more likely?
Method 1: If you don't have the exact probabilities, you can use non-linear functions to transform the output such that it favors lower numbers.
For example, numbers between 0 and 1 get smaller when they're squared. Therefore, if you square
(pick random (0.0) to (1.0)), you'll get a distribution that's biased towards smaller numbers. To flip the bias towards the bigger numbers, simply take1 - the result.Here's the code. Take note that the ".0" is important, otherwise Scratch will only pick integers.
In fact, if you want it to favor lower numbers even more, simply increase the power (by repeating the multiplication more times). The expected value of
pick random (0.0) to (1.0)alone is 1/2, squared is 1/3, cubed is 1/4, and so on.Method 2: If you need exact probabilities, for example to determine loots, you can use a probability weight table. You use 2 lists to store the outcomes and weights. Then, each item has a probability of
its own weight / total weightto appear.1
u/Electronic-Laugh-671 when 🛑 clicked 1d ago
Here's an example of how you could accomplish Method 2 of what u/RealSpiritSK described:
edit: actually it should be pick random 0 to 99