![]() |
VOOZH | about |
In C++, we can simulate a dice roll by generating random numbers within a specific range. In this article, we will learn how to generate random values by dice roll in C++.
Example:
Input:
Roll a dice
Output:
Dice roll result is: 4
To simulate a dice roll, we can use the <random> library in C++. We will generate a random number between 1 and 6 (inclusive), which corresponds to the possible outcomes of a six-sided dice roll.
- Define a range (here to 1 to 6 inclusive).
- Seed an mt19937 object gen with the time-generated seed.
- Now, create a uniform_int_distribution<> object distrib. This models a random number generator that produces uniformly distributed integers within a specified range. Pass the minimum and maximum values of the range as parameters.
- Call the distributor by passing the generator as a parameter to get a generate a random number in a range.
- Finally, print the generated random number.
The below program demonstrates how we can simulate a dice roll in C++.
Dice roll result is: 2
Time Complexity: O(1)
Auxiliary Space: O(1)