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?
3 Answers
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.
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.
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.

That makes sense. I was mainly trying to understand the arrangement and weighting logic, not create a cryptographically secure random-number generator.