From fbcd9ae70029929a3e4d73d19b9ba7d303b03145 Mon Sep 17 00:00:00 2001
From: Michael Guttmann <michael.guttmann@student.tugraz.at>
Date: Wed, 21 Apr 2021 20:20:30 +0200
Subject: [PATCH] singleton + random

---
 2021-oop1/ku/stream-05/Dice.cpp | 31 +++++++++++++++++++++++++++++++
 2021-oop1/ku/stream-05/Dice.hpp | 23 +++++++++++++++++++++++
 2021-oop1/ku/stream-05/main.cpp | 24 ++++++++++++++++++++++++
 3 files changed, 78 insertions(+)
 create mode 100644 2021-oop1/ku/stream-05/Dice.cpp
 create mode 100644 2021-oop1/ku/stream-05/Dice.hpp
 create mode 100644 2021-oop1/ku/stream-05/main.cpp

diff --git a/2021-oop1/ku/stream-05/Dice.cpp b/2021-oop1/ku/stream-05/Dice.cpp
new file mode 100644
index 0000000..427cb94
--- /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 0000000..d903fce
--- /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 0000000..398a9fd
--- /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;
+}
-- 
GitLab