# Thread: generate random quality ratings

1. ## generate random quality ratings

Hello,
For this program I have to write I need to generate items randomly and put them in a stack. Each item has an id number in the order it was made and a rating which is completely random, E,G,M and D. D will only occur 10% of the time. I am not to familiar with the libraries so I'm not sure if one can help me or if I have to write that part myself. I included our instructions so anyone willing to help can better understand what I have to do.

2. Have you tried to write some code? Can you show us what you have tried, so we can help you?

3. well I got it to generate random ratings but the problem is that it randomly generates the same ratings over and over and since this function (which I have as its own program right now) will be called at different times it will just give me the same ratings. And I still have no clue how to make D occur only 10 percent of the time but here it is:

Code:
```#include <stdio.h>

int main()
{
int i, x = 1, y = 5, z, numb;

scanf("%d", &numb);

for (i = 0; i < numb; i++)
{
z = rand() % (y - x) + x;
switch (z)
{
case 1:
z=1;
printf("E\n");
break;
case 2:
z=2;
printf("G\n");
break;
case 3:
z=3;
printf("M\n");
break;
case 4:
z=4;
printf("D\n");
break;
}
}

return 0;
}```

4. The reason you are getting the same values every time is because you aren't seeding the generator.
Code:
`srand( (unsigned) time(NULL) );`

But for testing purposes having the same values can be helpful.

Easy way to get D to only appear 10% of the time.

Instead of using rand() % (y-x) + x using rand() % 10 + x; Then if z is between 1 and 3 (inclusive) then its E, if between 4 and 6 inclusive then its G, if its between 7 and 9 inclusive its M, and finally if its 10 its D.

5. It worked great... thanks a lot for your help

6. A variation of Thantos' suggestion...
Code:
```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

char foo(void)
{
static const char letter[] = {'E','E','E','G','G','G','M','M','M','D'};
/* http://www.eskimo.com/~scs/C-faq/q13.16.html */
return letter [ rand() / (RAND_MAX / sizeof letter + 1) ];
}

int main(void)
{
int i, E = 0, G = 0, M = 0, D = 0;
srand(time(0));
for ( i = 0; i < 1000000; ++i )
{
switch ( foo() )
{
case 'E': ++E; break;
case 'G': ++G; break;
case 'M': ++M; break;
case 'D': ++D; break;
}
}
printf("E = %.1f%%, G = %.1f%%, M = %.1f%%, D = %.1f%%\n",
(100.0 * E) / i, (100.0 * G) / i, (100.0 * M) / i, (100.0 * D) / i);
return 0;
}

/* my output
E = 30.0%, G = 30.1%, M = 29.9%, D = 10.0%
*/```