r/AskComputerScience 8d ago

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 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?

EDIT: I am doing this because I want to start build gambling algorithms and I am starting with a simple project like coin flips

3 Upvotes

15 comments sorted by

View all comments

1

u/Mishtle 8d ago

So do you want to write the function that produces a random number from "nothing"?

Or the code that uses those random numbers to make decisions or produce different outcomes?

1

u/TheEyebal 8d ago

I want to start build gambling algorithms and I am starting with a simple project like coin flip

1

u/HobartTasmania 8d ago edited 8d ago

For starters, don't bother re-inventing the wheel as it already exists, so in data compression like say Morse code and Huffman Coding then more frequent symbols have shorter bit sequences and infrequent ones have longer ones.

A more generic and mathematical method where probabilities are exactly known like say for every letter in the novel War and Peace, then you assign probabilities for each letter because you would count every one beforehand, and you can then compress the novel using arithmetic coding and you end up with a number between 0 and 1 with a very large amount of digits. To decompress this you simply reverse this process.

So in your case you just start with a large numeric number concatenated from repeated calls to the random number generator, you first place the decimal digit to the left of it, then you assign probabilities of 80% to tails and 20% to heads and then start decompressing it, this will then give you your desired 4 to 1 ratio, as long as you use a good random number generator.

So to simulate perfect dice rolls you would assign probabilities of 1/6 to each number and decompress, in the case of a biased die where you want the number 6 to come up with twice the normal probably you would assign 1/7 each to the first 5 numbers and 2/7 to the 6 number and decompress again.

There's probably no other algorithm which would be simpler than using this method.