Advertisement
Saand1338

Dice simulator

Jun 26th, 2014
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. /** C++ headers **/
  2. #include <iostream>
  3. #include <vector>
  4. #include <limits>
  5.  
  6. /** C headers **/
  7. #include <ctime>
  8.  
  9. /** constants **/
  10. #define DICESIDES 6
  11. // the maximum number an integer can hold on my system.
  12. #define NUM_SIMS std::numeric_limits<int>::max()
  13.  
  14. // generate a random integer (through the standard C rand function) bound by a
  15. // lower and upper value
  16. int getRandomInt(int min, int max)
  17. {
  18.     return rand() % (max + 1 - min) + min;
  19. }
  20.  
  21. int main (int argc, char * const argv[]) {
  22.     // Set the random seed to time.
  23.     srand(time(NULL));
  24.        
  25.     // making a "grab-bag" of dice values. This could theoretically be used for
  26.     // any D[X] dice simulation.
  27.     std::vector<int> singleDie (DICESIDES);
  28.     for(int i = 0; i < DICESIDES; i += 1) {
  29.         singleDie.at(i) = i + 1;
  30.     }
  31.        
  32.     // lets keep track of all these
  33.     std::vector<int> results (DICESIDES);
  34.     for(int i = 0; i < DICESIDES; i += 1) {
  35.         results.at(i) = 0;
  36.     }
  37.    
  38.     // lets simulate NUM_SIMS rolls.
  39.     for(int i = 0; i < NUM_SIMS; i += 1) {
  40.         for(int j = 0; j < DICESIDES; j += 1) {
  41.             int roll = getRandomInt(0, DICESIDES - 1);
  42.             int temp = singleDie.at(j);
  43.             singleDie.at(j) = singleDie.at(roll);
  44.             singleDie.at(roll) = temp;
  45.         }
  46.        
  47.         results.at(singleDie.at(0) - 1) += 1;
  48.        
  49.         // every billion iterations
  50.         if(i % 1000000000 == 0 && i > 0) {
  51.             std::cout << i << " iterations." << std::endl;
  52.         }
  53.     }
  54.    
  55.     // Print the results
  56.     std::cout << "Number of simulations: " << NUM_SIMS << std::endl;
  57.     for(int i = 0; i < DICESIDES; i += 1) {
  58.         float percentage = ((float)(results.at(i)) / (float)(NUM_SIMS)) * 100.0f;
  59.         std::cout << "Result: " << i + 1 << ": " << results.at(i) << " (" << percentage
  60.                   << "%)" << std::endl;
  61.     }
  62.    
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement