Generating Random Values Similar to a Dice Roll
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.
Approach:
- 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.
C++ Program to Generate Random Values by Dice Roll
The below program demonstrates how we can simulate a dice roll in C++.
// C++ program to simulate a dice roll
#include <iostream>
#include <random>
#include <ctime>
using namespace std;
int main()
{
// Define range
int min = 1;
int max = 6;
// Initialize a random number generator
mt19937 gen(time(0));
uniform_int_distribution<> distrib(min, max);
// Generate random number in the range [min, max]
int randomValue = distrib(gen);
cout << " Dice roll result is: " << randomValue << endl;
return 0;
}
Output
Dice roll result is: 2
Time Complexity: O(1)
Auxiliary Space: O(1)
How to Generate Random Value by Dice Roll in C++?
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