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

14,938

Solution 1

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.

Solution 2

If you have a pre-defined set of values you want to choose from randomly, then put them in an array, and use rand to get the index into the array.

See e.g. this old SO answer for how to get a random number within a range (i.e. between zero and the size of the array for your case).

Share:
14,938
kevin gomes
Author by

kevin gomes

Updated on June 23, 2022

Comments

  • kevin gomes
    kevin gomes almost 2 years
    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.

  • chouaib
    chouaib almost 10 years
    you mean r = myArray[rand()%6] right? otherwise why you defined muArray ?
  • progrenhard
    progrenhard almost 10 years
    @chouaib fixed it, to make more sense thanks. I got a little lazy.