Advertisement
Guest User

Untitled

a guest
Jul 29th, 2015
395
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.98 KB | None | 0 0
  1.  
  2. #include <stdlib.h>
  3. #include <signal.h>
  4. #include <stdio.h>
  5. #include <time.h>
  6.  
  7. #define N 16
  8.  
  9. static int done = 0;
  10.  
  11. static void end(int sig)
  12. {
  13.     done = 1;
  14. }
  15.  
  16. int main(int argc, char **argv)
  17. {
  18.     time_t seed = time(NULL);
  19.     if (argv[1]) {
  20.         seed = atoi(argv[1]);
  21.     }
  22.     srand(seed);
  23.  
  24.     // Set the handler so we finish cleanly
  25.     signal(SIGINT, end);
  26.  
  27.     int width = 0;
  28.     {
  29.         int c = N;
  30.         while (c) {
  31.             width++;
  32.             c /= 10;
  33.         }
  34.     }
  35.  
  36.     // Print initial layout
  37.     for (int i = 0; i < N; i++) {
  38.         printf("%*d: 0\n", width, i);
  39.     }
  40.  
  41.     unsigned long hits[N] = {};
  42.     unsigned long n = 0;
  43.     while (!done) {
  44.         n++;
  45.         printf("\r\e[%dA", N);
  46.  
  47.         hits[rand() % N]++;
  48.         for (int i = 0; i < N; i++) {
  49.             printf("%*d: %f\n", width, i, (double)hits[i] / n);
  50.         }
  51.         printf("Iterations: %lu", n);
  52.     }
  53.  
  54.     // Print one last time for cleanliness
  55.     printf("\r\e[%dA", N);
  56.     for (int i = 0; i < N; i++) {
  57.         printf("%*d: %f\n", width, i, (double)hits[i] / n);
  58.     }
  59.     printf("Iterations: %lu\n", n);
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement