allocator

weighted random example

May 15th, 2013
479
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.83 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <memory.h>
  5.  
  6. int main()
  7. {
  8.     // Input
  9.     int n = 4;
  10.     int attempts = 100000;
  11.     char *title[] = {"Red", "Green", "Blue", "Unknown"};
  12.     double weight[] = {0.4, 0.1, 0.2, 0.3};
  13.  
  14.     srand(time(0));
  15.  
  16.     // Prefix sum
  17.     double sum[n + 1];
  18.     sum[0] = 0;
  19.     for (int i = 0; i < n; ++i)
  20.         sum[i + 1] = sum[i] + weight[i];
  21.  
  22.     int hits[n];
  23.     memset(hits, 0, n * sizeof(hits[0]));
  24.     int turn = attempts;
  25.     while (turn--) {
  26.         double p = (double)rand() / RAND_MAX * sum[n];
  27.         int pos;
  28.         for (pos = 0; sum[pos + 1] < p; ++pos); // change to binary search & epsilon compare
  29.         hits[pos]++;
  30.     }
  31.  
  32.     for (int i = 0; i < n; ++i)
  33.         printf("%s %f\n", title[i], (double)hits[i] / attempts);
  34.  
  35.     return 0;
  36. }
Add Comment
Please, Sign In to add comment