How can I generate a random sequence with exactly four heads and one tail?
Asked by
text_12em
I'm building a coin-flipping example where every five-flip sequence must contain exactly four Heads and one Tail, but the Tail should appear in a random position. I'd like to understand and implement the logic myself rather than simply relying on a ready-made weighted-random library. What algorithm or step-by-step approach should I use?
Answers
Treat the required results as a collection containing [Heads, Heads, Heads, Heads, Tail], then shuffle that collection. A FisherโYates shuffle is a good algorithm to study and implement yourself. After shuffling, read the elements from left to right. Every result will contain exactly four Heads and one Tail, while each position can vary.
Reply to this answer
Start by describing the process in plain language: create five slots, put four Heads and one Tail into them, choose positions to swap using random indexes, and repeat until the collection is shuffled. Then translate each step into code and test it many times. Check that every output has four Heads and one Tail, and count how often the Tail appears in each position. With a fair shuffle, the five positions should occur at roughly similar rates over a large number of trials.
Reply to this answer
There are two separate problems here: creating randomness and arranging the fixed outcomes. FisherโYates handles the arrangement, but it still needs a random index at each step. If you avoid the languageโs random-number library, youโll need to implement a pseudorandom number generator and seed it somehow. For learning, itโs usually better to use the built-in generator first and focus on understanding the shuffle.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions