| Rolling - Random Numbers; Learn how to generate random numbers | |
|---|---|
| Tweet Topic Started: Apr 1 2009, 07:20 AM (80 Views) | |
| RedMage1993 | Apr 1 2009, 07:20 AM Post #1 |
|
Administrator
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
|
We were asked in CS today to create a program that keeps track of how many times you needed to roll dice until all dice were on a different side (number). I wrote it in C++ first: //-------------------- // author: fritz ammon // // rolling.cpp (C++) -- // how many times do you // have to roll to get three // different numbers //-------------------- #include <iostream> #include <ctime> #include <cstdlib> using namespace std; // function prototype(s) //---------------------- void RollDice(); //---------------------- // RollDice updates 3 dice with random numbers // global variable(s) //------------------- int di1, di2, di3; // dice //------------------- // main //----- int main() { int rollCount = 0; // initialize di1 = 0; di2 = di1; di3 = di2; srand((unsigned)time(0)); // make sure random on execute; requires ctime while (di1 == di2 || di1 == di3 || di2 == di3) { RollDice(); rollCount++; cout << rollCount << ". " << di1 << " " << di2 << " " << di3 << endl; } cout << endl; cout << "It took " << rollCount << " roll(s) to get three different numbers: \n" << di1 << " " << di2 << " " << di3; cin.get(); return 0; } //----- // RollDice //--------- void RollDice() { // generate three random numbers const int LOW = 1; const int MAX = 6; const int RANGE = (MAX - LOW) + 1; di1 = LOW + int(RANGE * rand() / (RAND_MAX + 1.0)); // RAND_MAX requires cstdlib di2 = LOW + int(RANGE * rand() / (RAND_MAX + 1.0)); di3 = LOW + int(RANGE * rand() / (RAND_MAX + 1.0)); } |
![]() |
|
| RedMage1993 | Nov 12 2013, 08:57 PM Post #2 |
|
Administrator
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
|
that is an interesting thing to keep track of, but for the sake of knowing how to evade having to keep rolling, one thing i did once was: 1. create a list of all the numbers you would like to use 2. roll an index number 3. when that number is used, remove it from the list 4. repeat and you you no longer have to worry about landing the same number |
![]() |
|
| 1 user reading this topic (1 Guest and 0 Anonymous) | |
| « Previous Topic · Main (start here) · Next Topic » |





![]](http://z3.ifrm.com/static/1/pip_r.png)



4:43 PM Jul 10