Weighted dice roll

I need a way to make a weighted dice roll

Basically generate a random 0 or 1 based on 2 values whatever is higher has a greater chance of getting picked but not guaranteed

untitled script pic - 2023-04-12T082928.084
In this example, the 0 has a 60% chance to be picked, whereas the 1 has a 40% chance to be picked. However, either number could be chosen.

Here is another example:
untitled script pic - 2023-04-12T083154.798
Again, the 0 has a 60% chance to be chosen (while the 1 has a 40% chance), but in this example, it is a lot easier to tweak the odds - just change the 6 and the 4 to whatever values you want.

That’s helpful but is there a way to make it into a custom block that works a bit more logical
I need it for the ai system that uses probability to calculate between 2 actions

I don't know what you mean by "more logical", but it is quite easy to put the solution I provided into a custom block. untitled script pic - 2023-04-12T083740.313

Yea that makes a bit more sense, what I meant by logical is turning it into a percentage

So like < ()% chance of true> and then using the 2 values to work out what the chance of true should be

So something like this?
untitled script pic - 2023-04-12T084256.856
Then there is a (percent) chance of reporting true.

Yea that works! Thank you!

I also made my own version that a is a bit more lightweight but idk if it’s correct
untitled script pic 4

hmmm i think its kinda identical in a way but cant really tell one sec also did you need me for anything cookieclickerer?

No, I think that works. Definitely a lot more lightweight.

Not right now, but maybe you should work on chapter 2

Now I need a way to calculate the chance to do the other thing from just the first chance

Here’s a more general solution, working for any number of possible outcomes (values) and corresponding weights (not necessarily adding up to 1):


Programming tools SANDBOX script pic 64

Update: more efficient implementations of CUMULATIVE are included in topic: How do I implement a simple JavaScript function in Snap!, from post #3 onwards.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.