Advertisement
dmilicev

test_of_c_function_rand()_v1.c

Nov 12th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. /*
  2.  
  3.     test_of_c_function_rand()_v1.c
  4.  
  5.  
  6.     You can find all my C programs at Dragan Milicev's pastebin:
  7.  
  8.     https://pastebin.com/u/dmilicev
  9.  
  10. */
  11.  
  12. #include <stdio.h>
  13. #include <stdlib.h>         // for RAND_MAX = 32767
  14. #include <time.h>           // for random numbers, for function rand()
  15.  
  16.  
  17. int main()
  18. {                           // try n = 10, 100, 1000, RAND_MAX
  19.                             // try repeat_times = 1, 10, 100, 1000, RAND_MAX = 32767
  20.     int i, j, n=100, repeat_times=RAND_MAX;
  21.     int random_number, pass_of_loop=0, min_appearance, max_appearance;
  22.     int counter_array[RAND_MAX];            // array to count frequency of random numbers
  23.     time_t t;                               // for random number generator
  24.  
  25.  
  26.     // Intializes random number generator, should only be called once.
  27.     //srand((unsigned) time(0));
  28.     srand((unsigned) time(&t));
  29.  
  30.     // reset all n counters in counter_array[] to 0
  31.     for( i=0; i<n; i++ )
  32.         counter_array[i] = 0;
  33.  
  34.     // counting the pass_of_loop of random numbers
  35.     for( j=0; j<repeat_times; j++ )
  36.     {
  37.         for( i=0; i<n; i++ )
  38.         {
  39.             random_number = rand() % n;     // random number between 0 and n-1
  40.             counter_array[random_number]++; // increase the corresponding counter
  41.         }
  42.  
  43.         // count and display loop passes
  44.         printf("\n %8d. pass of loop ", ++pass_of_loop);
  45.     }
  46.  
  47.  
  48.     // finding the lowest and highest pass_of_loop
  49.     min_appearance = counter_array[0];          // we assume it is the smallest
  50.     max_appearance = 0;                         // we assume it is the largest
  51.  
  52.     for( i=0; i<n; i++ )
  53.     {
  54.         if( min_appearance > counter_array[i] )
  55.             min_appearance = counter_array[i];
  56.  
  57.         if( max_appearance < counter_array[i] )
  58.             max_appearance = counter_array[i];
  59.     }
  60.  
  61.  
  62.     // print the number of occurrences of random numbers
  63.     for( i=0; i<n; i++ )
  64.         printf("\n %7d %7d ", i, counter_array[i] );
  65.  
  66.     // print the lowest and highest frequency
  67.     printf("\n\n highest frequency is %7d \n", max_appearance );
  68.     printf("\n lowest frequency is  %7d \n", min_appearance );
  69.     printf("\n %7d    - %7d = %5d \n",
  70.             max_appearance, min_appearance, max_appearance - min_appearance );
  71.  
  72.  
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement