From 146d1716ef29a3589f0492d141fa06a2252f7bcc Mon Sep 17 00:00:00 2001 From: newt Date: Wed, 9 Oct 2024 18:02:42 +0100 Subject: [PATCH] feat(c++): oop dice - --- languages/c++/CMakeLists.txt | 1 + languages/c++/code/dice.cc | 67 ++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 languages/c++/code/dice.cc diff --git a/languages/c++/CMakeLists.txt b/languages/c++/CMakeLists.txt index c10e694..9d2e238 100644 --- a/languages/c++/CMakeLists.txt +++ b/languages/c++/CMakeLists.txt @@ -9,3 +9,4 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) add_executable(pascal code/pascal.cc) add_executable(babylonian code/babylonian.cc) add_executable(karatsuba code/karatsuba.cc) +add_executable(dice code/dice.cc) diff --git a/languages/c++/code/dice.cc b/languages/c++/code/dice.cc new file mode 100644 index 0000000..df9791a --- /dev/null +++ b/languages/c++/code/dice.cc @@ -0,0 +1,67 @@ +#include +#include +using namespace std; + +class Dice { + private: + int randomInteger(int lowerBound, int upperBound) { + return rand() % (upperBound - lowerBound - 1) + 1; + } + + public: + int sides; + + // Constructor + Dice(int sideNum) { + // Set the number of sides + sides = sideNum; + } + + // Roll the dice + int roll() { + return randomInteger(1, sides); + } + + // Roll the dice many times and return thre result in a vector + vector rollMany(int times) { + vector rolls{}; + + for (int i = 0; i < times; i++) { + int rolled = roll(); + rolls.push_back(rolled); + } + + return rolls; + } +}; + +// Print a vector of integers onto one line +void printResults(vector data) { + int length = data.size(); + + for (int i = 0; i < length; i++) { + string out = to_string(data[i]); + if (i != length - 1) out += ", "; + + cout << out; + } +} + +int main() { + // Seed the RNG + srand((unsigned)time(nullptr)); + + // Instantiate the dice + Dice six(6); + Dice twenty(20); + + // Roll them + vector sixRolled = six.rollMany(10); + vector twentyRolled = twenty.rollMany(10); + + // Display their outputs + cout << "Six Sided Dice:" << endl; + printResults(sixRolled); + cout << endl << endl << "Twenty Sided Dice:" << endl; + printResults(twentyRolled); +}