pinocchio

rand7 w/ rand5 in C

Mar 29th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <math.h>
  5.  
  6. int counter7[7] = {0, 0, 0, 0, 0, 0, 0};
  7.  
  8. int rand5 ()
  9. {
  10.   return rand () % 5 + 1;
  11. }
  12.  
  13.  
  14. int rand7 ()
  15. {
  16.   int r = 0;
  17.   while (r == 0)
  18.     {
  19.       int bits[3] = {0, 0, 0};
  20.       int v = 3;
  21.      
  22.       for (int i = 0; i < 3; i ++)
  23.     {
  24.       while (v == 3)
  25.         v = rand5 ();
  26.      
  27.       if (v < 3)
  28.         bits[i] = 1;
  29.      
  30.       v = 3;
  31.     }
  32.      
  33.       r = (bits[2] << 2) | (bits[1] << 1) | (bits[0]);
  34.     }
  35.  
  36.   return r;
  37. }
  38.  
  39.  
  40. int main ()
  41. {
  42.   int v;
  43.   srand(time(NULL));
  44.  
  45.   for (int i = 0; i < 10000000; i++)
  46.     {
  47.       v = rand7 ();
  48.       counter7[v - 1] += 1;
  49.     }
  50.  
  51.  
  52.   for (int i =0; i < 7; i++)
  53.     {
  54.       printf("%f\n", counter7[i]/10000000.0);
  55.     }
  56.  
  57.   return 0;
  58. }
  59.  
  60.  
  61. loris@leibniz:~/sandbox$ g++ test.c -o test
  62. loris@leibniz:~/sandbox$ ./test
  63. 0.143061
  64. 0.142927
  65. 0.142746
  66. 0.142812
  67. 0.143001
  68. 0.142784
  69. 0.142670
Advertisement
Add Comment
Please, Sign In to add comment