diff --git a/2021-oop1/ku/stream-05/Dice.cpp b/2021-oop1/ku/stream-05/Dice.cpp new file mode 100644 index 0000000000000000000000000000000000000000..427cb946c272c379b3d6759fb853cc5b2a0f52a7 --- /dev/null +++ b/2021-oop1/ku/stream-05/Dice.cpp @@ -0,0 +1,31 @@ +#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_); +} diff --git a/2021-oop1/ku/stream-05/Dice.hpp b/2021-oop1/ku/stream-05/Dice.hpp new file mode 100644 index 0000000000000000000000000000000000000000..d903fce440d60d4a3d9d5d867bcc07683a220a9c --- /dev/null +++ b/2021-oop1/ku/stream-05/Dice.hpp @@ -0,0 +1,23 @@ +#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 diff --git a/2021-oop1/ku/stream-05/main.cpp b/2021-oop1/ku/stream-05/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..398a9fdd84f3fa0db5f992bf9861029e1cacde98 --- /dev/null +++ b/2021-oop1/ku/stream-05/main.cpp @@ -0,0 +1,24 @@ +#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; +}