Search code examples
c++randommaxmindice

How can I find a minimum and maximum from a dice roll?


I want to find the minimum number, or maximum number, that I could possibly receive if put an X amount of dice and a X amount of dice sides. I know that if I only roll one dice then the minimum would be the "minrange" and the maximum would be the "minrange" + "numOfSides", but if I were to roll multiple dice with X amount of sides; how would I find the minimum/maximum number that could be generated?

double rollDice(int numOfDice, int numOfSides, int divide, int minrange) {
    int i = 0;
    subtotal = 0;
    while (i < numOfDice) {
        roll = 0;
        roll = minrange + (rand() % numOfSides);
        subtotal += roll;
        i++;
    }
    return subtotal / divide;
}

Solution

  • #include <iostream>
    
    void rollDice(int numOfDice, int numOfSides, int* minRange, int* maxRange) {
        *minRange = numOfDice;
        *maxRange = numOfDice * numOfSides;
        return;
    }
    
    int main() {
    
        int minRange;
        int maxRange;
        int noDice = 3;
        int noSides = 6;
    
        rollDice(noDice, noSides, &minRange, &maxRange);
    
        std::cout << "Minimum range for " << noDice << " dice with " << noSides << "sides is: " << minRange << std::endl;
        std::cout << "Maximum range for " << noDice << " dice with " << noSides << "sides is: " << maxRange << std::endl;
    
        return 0;
    }
    

    Firstly, slight mistake in your question, the maximum score for one dice would not be minRange + numOfSides, it would be numOfSides, and for an arbitrary number of dice the minimum score would be noDice * 1 = noDice and the maximum score would be noDice * noSides.

    Seen as you want to calculate the minimum and maximum totals of an arbitrary number of arbitrary sided dice, the best way to retrieve two values from a function, without creating a data structure or an array or an object is to use pointers. By passing the address of the variables to store the minRange and maxRange using the & operator the rollDice function can directly access the chunk of memory used to hold those variables and set them to the appropriate values.

    This is my first attempt at answering a question, hope it is what you are looking for.