Created
January 30, 2024 08:32
-
-
Save bwedding/08b54120bfdb22b1bf5c585e901f5a78 to your computer and use it in GitHub Desktop.
Random Dice Roller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <random> | |
#include <vector> | |
#include <array> | |
class Die { | |
public: | |
// Constructor for a 6-sided die | |
Die() : Die(6) {} | |
// Constructor for a die with an arbitrary number of sides | |
explicit Die(int numSides) : dist(1, numSides), sides(numSides) {} | |
// Method to roll the die | |
int roll() { | |
return dist(getEngine()); | |
} | |
// Method to analyze the distribution of rolls | |
void analyzeDistribution(int rolls) { | |
std::vector<int> counts(sides, 0); | |
for (int i = 0; i < rolls; ++i) { | |
++counts[roll() - 1]; | |
} | |
for (int i = 0; i < sides; ++i) { | |
std::cout << "Side " << (i + 1) << ": " << counts[i] << " times (" << static_cast<double>(counts[i]) / rolls * 100 << "%)" << std::endl; | |
} | |
} | |
private: | |
std::uniform_int_distribution<> dist; // Uniform distribution | |
int sides; // Number of sides on the die | |
static std::mt19937& getEngine() { | |
static std::random_device rd; // Random device to seed the generator | |
std::array<std::uint32_t, std::mt19937::state_size> seed_data; | |
std::generate_n(seed_data.data(), seed_data.size(), std::ref(rd)); | |
std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); | |
static std::mt19937 engine(seq); // Mersenne-Twister random number generator (seeded with seed_seq) | |
return engine; | |
} | |
}; | |
// Example usage | |
int main() { | |
Die sixSided; // Default 6-sided die | |
std::cout << "Analyzing the distribution of a 6-sided die over 10000 rolls:" << std::endl; | |
sixSided.analyzeDistribution(10000); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment