Random numbers between a specific set.

Hello guys. I was wondering if there is a function or a way to generate random numbers from a specific set of numbers. For example, let's say I want to generate random numbers between 56, 76, 134, 299, 452, 669 and only those numbers. Is there any way I can do that?
No, but it would be easy enough to create. How many numbers you want is the first question you must ask. In your situation it is 6 so you need to use

 
rand() % 6;


Now you can set up a switch statement so that - would return 56, 1 would return 76, 2 would return 134, etc... so that you can have a random number of just those 6 numbers.
You cannot do this the way you want to, though there is a way to cheat the system.

Do this:

1
2
3
4
5
6
7
8
srand (time(NULL));

int RandGen = rand() % 6 + 1;

if(RandGen == 1)
{
     [do something with 57]
}

This is a guess, I hope it works with you.
Last edited on
yup there is.

here's the pseudo code
# include<cstdlib> - include this for rand function
#include <ctime>

int Funtion for getting number()
{
int Random
int a,b,c,d,e,f = equaling your numbers you want picked from
int number returned from your options, lol.

srand(time(0)); - this line will seed random based on time in seconds which changes often so your numbers are more random. To use this you need to include ctime

Random = rand()%6+1 - generates random number between 1 -6

case 1 Random1
random number returned from options = 56
case 2 Random2
random number returned from options = 76
case 3 Random3
random number returned from options =134
case 4Random4
random number returned from options =299
case 5Random5
random number returned from options =452
case 6 random6
random number returned from options =669

return random number picked from your options.

}
Last edited on
closed account (D80DSL3A)
Here's another way.
1
2
3
int values[] = {56, 76, 134, 299, 452, 669};
int randomIndex = rand()%6;// generate an index value randomly
cout << "A random value from the list is: " << values[randomIndex];
lol, if I were you, I'd go with his way, but mine will work :P
also if you come back to check something you might want to seed random to time in fun2code's method. The idea behind random numbers, and computers, is that they're not really random. They're calculated using some algorithm. If you plan on using the same number generation over and over, you'll find that you may be getting predictable patterns. seeding random will give you a lot more randomness.
Topic archived. No new replies allowed.