Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- static int weighted_random()
- {
- int weights[] = { 50, 50 };
- int count = sizeof(weights) / sizeof(int);
- int sum = 0;
- for (int i = 0; i < count; ++i)
- {
- sum += weights[i];
- }
- int rnd = rand() % sum;
- int c = 0;
- for (int i = 0; i <= count; ++i)
- {
- if (rnd < c)
- {
- return i - 1;
- }
- c += weights[i];
- }
- return -1;
- }
- int main()
- {
- srand((unsigned)time(NULL));
- int randoms[2] = { 0, 0 };
- for (int i = 0; i < 10000000; ++i)
- {
- randoms[weighted_random()]++;
- }
- printf("weighted_random 0: %d\n", randoms[0]);
- printf("weighted_random 1: %d\n", randoms[1]);
- return 0;
- }
Add Comment
Please, Sign In to add comment