Link to home
Start Free TrialLog in
Avatar of skips2ndbase
skips2ndbase

asked on

Random Number Generation from a specified set

How do I go about generating a random number from a specified set?
For instance, I need to generate a number from the set { 1, 4, 7, 10, 13, 16);
Avatar of akshayxx
akshayxx
Flag of United States of America image

#define setsize 6 // u know ur set size;
int set[]={1,4,7,10,13,16};

srand(time(NULL));

int gimmeRandomFromSet(int *set,int setsize){
int j;
j=(int) (((float)setsize)*(rand()/(RAND_MAX+1.0)));
// above gives u random number between 0 and setsize;
// so ur random number is now..set[j]
return set[j];
}


calll it like this

gimmeRandomFromSet(set,setsize);
int randfromset=gimmeRandomFromSet(set,setsize);

now use randfromset
#include <iostream>
#include <stdlib.h>

using namespace std;

#define ARRAYSIZE 6

void main()
{
    srand(time(NULL));
    int set[]={1,4,7,10,13,16};
    cout << "Randomly generated " << set[rand()%size] << " from the specified set of numbers." << endl;
}

Dang!!! I forgot that I was in the C topic area. "-)

#include <stdio.h>
#include <stdlib.h>
#incldue <time.h>

#define ARRAYSIZE 6

int main()
{
   int set[]={1,4,7,10,13,16};
   srand(time(NULL));
   printf("Randomly generated %i from the specified set of numbers.\n",set[rand()%ARRAYSIZE]);
   return 0;
}

Exceter
ASKER CERTIFIED SOLUTION
Avatar of Exceter
Exceter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hmm i guess my solution was good enough.. whatever followed was just a rewrite..
anyways not for the first time with me