elvman

Weighted random

May 19th, 2016
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.79 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. static int weighted_random()
  6. {
  7.     int weights[] = { 50, 50 };
  8.     int count = sizeof(weights) / sizeof(int);
  9.  
  10.     int sum = 0;
  11.  
  12.     for (int i = 0; i < count; ++i)
  13.     {
  14.         sum += weights[i];
  15.     }
  16.  
  17.     int rnd = rand() % sum;
  18.  
  19.     int c = 0;
  20.  
  21.     for (int i = 0; i <= count; ++i)
  22.     {
  23.         if (rnd < c)
  24.         {
  25.             return i - 1;
  26.         }
  27.  
  28.         c += weights[i];
  29.     }
  30.  
  31.     return -1;
  32. }
  33.  
  34. int main()
  35. {
  36.     srand((unsigned)time(NULL));
  37.  
  38.     int randoms[2] = { 0, 0 };
  39.  
  40.     for (int i = 0; i < 10000000; ++i)
  41.     {
  42.         randoms[weighted_random()]++;
  43.     }
  44.  
  45.     printf("weighted_random 0: %d\n", randoms[0]);
  46.     printf("weighted_random 1: %d\n", randoms[1]);
  47.  
  48.     return 0;
  49. }
Add Comment
Please, Sign In to add comment