RNG: Dice Rolls and Coin Tosses
Simulating Dice and Coin Flips
This is going to be a rather short article because its a pretty simple concept, though one that comes up repeatedly on various programming forums: How to you simulate a coin toss or the roll of a dice?
When implementing a board game type program or a game of chance you WILL, at some point find your self needing to simulate the process of rolling dice or doing a coin toss. The easiest way to implement this is through (pseudo) random number generation. C++ had <random> in the STL, Java has java.util.Random, and javascript has Math,random(). In truth youll be hard pressed to find a programming language that doesn't have some kind of prng. I'm going to keep it old school in this article and use C-style rand() calls, because its portable to C and C++, as well perl and php. With that being said, the concept is the same in other programming languages, but the syntax will change.
Coin Toss
After flipping a coin, i've decided to go with simulating the coin toss first. I'm sure this doesn't need explaining but tossing a coin is supposed to give you a fair 50/50 probability that it will land on either heads or tails, and the person that calls which side it lands on wins. Using C's rand() call we can get an approximation of this effect with the following code:
Rolling The Dice
I'm going to make the assumption we're NOT playing dungeons and dragons and just need the result of a 6 sided dice roll. The only thing we need to do to accomplish this is generate a random number between 1 and 6 (inclusive) and return the result:
Conclusion
There you have it. I told you this was going to be a short one. Sweet and to the point, and it will work in a pinch. Don't forget to call srand(time(0)); at the beginning of int main() to ensure the number changes each run through. In the mean time, Happy Hacking!
-
How Many Hanukkah Candles?
-
Pratt Parsing: Top-Down Operator Precedence
-
Generating P-Code by AST Traversal
-
Ternary Search Tries: String Specific Ordered Symbol Tables
-
Digital Search Trees
-
Lossless Compression Part III: Huffman Coding
-
Lossless Compression Part II: The LZ77 Algorithm
-
Lossless Compression Part I: Working with Bits in a Byte Oriented World
-
Bottom Up AVL Tree: The OG Self-Balancing Binary Search Tree
-
A Different Take on Merge Sort: Binary Search Trees?
Leave A Comment