1
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.

kevin gomes
  • 1,775
  • 5
  • 22
  • 30
  • 1
    `rand()` is allowed to be thoroughly bad: https://stackoverflow.com/questions/24005459/implementation-of-the-random-number-generator-in-c-c – Deduplicator Jul 17 '14 at 17:07

4 Answers4

6

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.

progrenhard
  • 2,333
  • 2
  • 14
  • 14
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).

Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

You could get the list of random values that you want and store them in an array. Then you can choose a random number from the range of the list and choose the location at the specified index.

ruthless
  • 1,090
  • 4
  • 16
  • 36
0

You can divide the random number and take only the leftover. use is as a index of the array of your wanted numbers

For example , if you take the (random number % 3) you will get 0,1,2 so you can use array of 3 wanted numbers

Gil.I
  • 895
  • 12
  • 23