fork download
  1. // arbitrary size random integer from std::rand().
  2.  
  3. #include <stdlib.h>
  4. #include <stdint.h>
  5. #include <string.h>
  6. #include <limits.h>
  7. #include <assert.h>
  8. #include <stdio.h>
  9. #include <time.h>
  10.  
  11. // can be any unsigned type.
  12. typedef uint32_t uint_type;
  13. #define RAND_UINT_MAX ((uint_type) -1)
  14.  
  15. uint_type rand_uint(void)
  16. {
  17. // these are all constant and factor is likely a power of two.
  18. // therefore, the compiler has enough information to unroll
  19. // the loop and can use an immediate form shl in-place of mul.
  20. uint_type factor = (uint_type) RAND_MAX + 1;
  21. uint_type factor_to_k = 1;
  22. uint_type cutoff = factor ? RAND_UINT_MAX / factor : 0;
  23. uint_type result = 0;
  24.  
  25. while ( 1 ) {
  26. result += rand() * factor_to_k;
  27. if (factor_to_k <= cutoff)
  28. factor_to_k *= factor;
  29. else
  30. return result;
  31. }
  32. }
  33.  
  34. int main(int argc, char* argv[])
  35. {
  36. #define BITS 2
  37. #define SIZE (1U << BITS)
  38.  
  39. size_t uintbit = sizeof(uint_type) * CHAR_BIT;
  40. assert(uintbit % BITS == 0);
  41.  
  42. srand(time(NULL));
  43. for ( int j = 0; j < uintbit/BITS; j++ ) {
  44. int bucket[SIZE] = {};
  45. // expect @ 1000 hits/bucket.
  46. // if any buckets are zero or too far off, something is wrong.
  47. for ( int i = 0; i < SIZE*1000; i++ )
  48. bucket[(rand_uint() >> j*BITS) % SIZE]++;
  49. for ( int i = 0; i < SIZE; i++ )
  50. printf("b[%-2d:%-2d) = %-4d ", j*BITS, (j+1)*BITS, bucket[i]);
  51. printf("\n");
  52. }
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 2168KB
stdin
Standard input is empty
stdout
b[0 :2 ) = 1044  b[0 :2 ) = 987   b[0 :2 ) = 962   b[0 :2 ) = 1007  
b[2 :4 ) = 968   b[2 :4 ) = 1010  b[2 :4 ) = 1057  b[2 :4 ) = 965   
b[4 :6 ) = 1035  b[4 :6 ) = 1006  b[4 :6 ) = 979   b[4 :6 ) = 980   
b[6 :8 ) = 997   b[6 :8 ) = 988   b[6 :8 ) = 1014  b[6 :8 ) = 1001  
b[8 :10) = 1004  b[8 :10) = 978   b[8 :10) = 1020  b[8 :10) = 998   
b[10:12) = 957   b[10:12) = 1056  b[10:12) = 995   b[10:12) = 992   
b[12:14) = 974   b[12:14) = 1004  b[12:14) = 1017  b[12:14) = 1005  
b[14:16) = 992   b[14:16) = 975   b[14:16) = 981   b[14:16) = 1052  
b[16:18) = 961   b[16:18) = 1034  b[16:18) = 987   b[16:18) = 1018  
b[18:20) = 1023  b[18:20) = 1007  b[18:20) = 1009  b[18:20) = 961   
b[20:22) = 1005  b[20:22) = 957   b[20:22) = 1014  b[20:22) = 1024  
b[22:24) = 1053  b[22:24) = 989   b[22:24) = 991   b[22:24) = 967   
b[24:26) = 1023  b[24:26) = 1028  b[24:26) = 942   b[24:26) = 1007  
b[26:28) = 951   b[26:28) = 1009  b[26:28) = 1017  b[26:28) = 1023  
b[28:30) = 1048  b[28:30) = 973   b[28:30) = 1011  b[28:30) = 968   
b[30:32) = 1015  b[30:32) = 1028  b[30:32) = 989   b[30:32) = 968