Skip to content
Snippets Groups Projects
Commit fbcd9ae7 authored by Guttmann, Michael's avatar Guttmann, Michael
Browse files

singleton + random

parent 2614aabe
No related branches found
No related tags found
No related merge requests found
#include "Dice.hpp"
Dice::Dice() : mt_(), distribution_(1, 6)
{
std::random_device rd;
mt_.seed(rd());
}
Dice& Dice::getInstance()
{
static Dice dice;
return dice;
}
unsigned int Dice::roll()
{
// return (mt() % 6) + 1; // ist problematisch
// Beispiel anhand eines 4-bit Integers, der Zahlen im Bereich [0, 15] darstellen kann.
// Wahrscheinlichkeiten der einzelnen Zahlen des Würfels:
// 1: 0, 6, 12 -> WSK = 3/16
// 2: 1, 7, 13
// 3: 2, 8, 14
// 4: 3, 9, 15
// 5: 4, 10 -> WSK = 2/16
// 6: 5, 11
// Damit ist das Ergebnis nicht "fair" bzw. gleichverteilt.
// Daher besser wie hier drunter die Gleichverteilung verwenden. :)
return distribution_(mt_);
}
#ifndef DICE_HPP
#define DICE_HPP
#include <random>
class Dice
{
private:
std::mt19937 mt_;
std::uniform_int_distribution<unsigned int> distribution_;
Dice();
Dice(const Dice& copy) = delete;
~Dice() = default;
public:
static Dice& getInstance();
unsigned int roll();
};
#endif // DICE_HPP
#include <iostream>
#include <string>
#include "Dice.hpp"
int main(int argc, char* argv[])
{
// Diese Methode kann an jeder beliebigen Stelle im Programm aufgerufen
// werden. Damit kann also immer auf den Würfel zugegriffen werden.
Dice& dice = Dice::getInstance();
for (size_t i = 0; i < 20; i++)
{
unsigned int result = dice.roll();
std::cout << "Roll number: ";
std::cout.width(2);
std::cout << i + 1;
std::cout.width(0);
std::cout << " - Result: " << result << std::endl;
}
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment