How can I generate a random sequence with exactly four Heads and one Tail?
Asked by
pollen-free.zone
I'm learning probability and want to build a small coin-flip program where every five-flip sequence contains exactly four Heads and one Tail, but the position of the Tail is random. I'd like to understand how to implement this myself rather than relying entirely on a ready-made weighted-random library. What algorithm or steps should I use?
Answers
Break the problem into two separate parts: deciding the allowed results and generating randomness. Your allowed results are all arrangements of four Heads and one Tail. Once you know that, either shuffle a prepared list or select one of the five possible Tail positions. Building a complete random-number generator from scratch is a much larger task; for learning, itโs fine to implement the shuffle logic yourself while using a basic random-number source provided by the language.
Reply to this answer
Treat the result as a collection containing four "Heads" values and one "Tail" value, then randomly shuffle that collection. After shuffling, read the entries from left to right. The FisherโYates shuffle is the standard algorithm for doing this. It produces every possible position for the Tail with equal probability, assuming the random number source is unbiased.
Reply to this answer
You can also choose the Tailโs position directly: generate a random integer from 0 through 4, put "Tail" at that index, and put "Heads" in the other four positions. This is simpler for this specific example and guarantees the required counts. For a general weighted system, you would usually assign each outcome a weight, choose a random value within the total weight, and select the corresponding range.
Reply to this answer
Add your answer
Answers are reviewed before publication.
pollen-free.zone: That makes sense. I was mainly trying to understand the arrangement and weighting logic, not create a cryptographically secure random-number generator.