selecting a random number from a set of numbers

How can i generate a random number from a set of numbers?

i m a beginner and i have been trying this, but cant find a solution.
this is the part of the code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int bestpro(int a[], int val)
{
    int count = 0, n;
    int l[4];
    for(int i=0; i < JOBS; i++)
    {
         if (a[i] == val)
         count++;
    }
    if (count >= 2)
    {
         for(int i=0; i<JOBS; i++)
         {
              if (a[i] == val)
              l[i] = 1;
              else
              l[i] = 0;
         }
    }
    else
    {
         for(int i=0; i < JOBS; i++)
         {
             if (a[i] == val)
             return i;
             else
             continue;
         }      
    }      
}

here i have to select a random number for which l[i] = 1. i.e. to select a random index i for which l[i] = 1... so i have to return the index basically.
AND value of JOBS = 4...

Suppose for i = 0,2,3 l[i] = 1, i have to select a random number from 0, 2 and 3 and return it...

And i use this function in a loop, so it is executed a number of times and each time the values are different.. like in the next loop, l[i] = 1 for 1 and 3, so i have to select a random number from 1 and 3 and return that.


how do i go about it?
Last edited on
How about?

1
2
3
4
5
int choice(int choices[])
{
     int n = sizeof(choices)/sizeof*choices[0]);
     return(choices[rand() % n]);
};


Use as choice({0,2,3}) or something like.
I didn't test it BTW, so it might have errors.
Thanks...
Topic archived. No new replies allowed.