Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <memory.h>
- int main()
- {
- // Input
- int n = 4;
- int attempts = 100000;
- char *title[] = {"Red", "Green", "Blue", "Unknown"};
- double weight[] = {0.4, 0.1, 0.2, 0.3};
- srand(time(0));
- // Prefix sum
- double sum[n + 1];
- sum[0] = 0;
- for (int i = 0; i < n; ++i)
- sum[i + 1] = sum[i] + weight[i];
- int hits[n];
- memset(hits, 0, n * sizeof(hits[0]));
- int turn = attempts;
- while (turn--) {
- double p = (double)rand() / RAND_MAX * sum[n];
- int pos;
- for (pos = 0; sum[pos + 1] < p; ++pos); // change to binary search & epsilon compare
- hits[pos]++;
- }
- for (int i = 0; i < n; ++i)
- printf("%s %f\n", title[i], (double)hits[i] / attempts);
- return 0;
- }
Add Comment
Please, Sign In to add comment