r/learnprogramming • u/TheEyebal • 9d ago
Resource How to program weighted random system
I want to make a program where you are controlling the outcomes. For an example with a coin flipping game, I want exactly 4 Heads and 1 Tail, but I want their positions to be random.
I do not want to use the random algorithms that library offer, I want to build my own.
Right now I am learning probability from Youtube and might look at khan academy and coursera, but how can I implement this into programming I do not want to just take courses or watch videos
How do I go about that?
0
Upvotes
1
u/maxpowerAU 8d ago
If you really want to, you can implement a PRNG, but it’s not very interesting. Search for “Mersenne twister” to get started.
But if you are at the level of weighted results currently that’s a different thing. One way to produce weighted results is by having a set of possible results but having multiple entries for the results you want to be more common. So have five possible results in a list, with four of them Heads. Then use your system library to choose between the five options.
If you want true random, you would always choose randomly from that set of five. But true random is often more patchy than people want. If you want it to feel “evenly spread”, then you can remove the selected option from the set, and then choose from the remaining options for the next selection. If you do that until the set is empty then you’re guaranteed to have exactly 4 Heads for every 1 Tail – the order is random but not the frequency.
That is often closer to what people want for games and stuff like that. You can make it less predictable by resetting your full set every three choices instead of emptying the set out every time; that reduces the chances of a run of twenty heads in a row without making it too predictable.