Search code examples
crandomsrand

How to generate random number from a given set of values?


int main()
{
    srand(time(NULL));
    int r=rand();
}

The above function can generate any number, but what if I want to generate a number from a given set of values.
For example if I want to generate a number randomly but ONLY from the values 4,6,1,7,8,3.
Is there any way to achieve this?

Any help would be appreciated.


Solution

  • It's pretty simple. Create an array. that has the outputs you desire (4,6,1,7,8,3). Then choose a random bucket in the array. % 6 basically chooses values 0 - 5 which are the indices in your array.

    int main()
    {
        srand(time(NULL));
        int myArray[6] = { 4,6,1,7,8,3 };
        int randomIndex = rand() % 6;
        int randomValue = myArray[randomIndex];
    }
    

    Some information on how you can manipulate rand() further.

    rand() % 7 + 1

    Explanation:

    • rand() returns a random number between 0 and a large number.

    • % 7 gets the remainder after dividing by 7, which will be an integer from 0 to 6 inclusive.

    • 1 changes the range to 1 to 7 inclusive.