Advertisement
wowonline

Untitled

Nov 23rd, 2021
614
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include <sys/wait.h>
  4. #include <stdlib.h>
  5.  
  6. enum
  7. {
  8.     MUL = 1103515245U,
  9.     INC = 12345U,
  10.     MOD = 2147483648U
  11. };
  12.  
  13. typedef struct RandomGenerator RandomGenerator;
  14. static int next(RandomGenerator *rr);
  15. static void destroy(RandomGenerator *rr);
  16.  
  17. typedef struct RandomOperations
  18. {
  19.     int (*next) (RandomGenerator *rr);
  20.     void (*destroy) (RandomGenerator *rr);
  21. } RandomOperations;
  22.  
  23. static const RandomOperations ops = {&next, &destroy};
  24.  
  25. typedef struct RandomGenerator
  26. {
  27.     unsigned int current;
  28.     const struct RandomOperations *ops;
  29. } RandomGenerator;
  30.  
  31.  
  32. static int next(RandomGenerator *rr)
  33. {
  34.     unsigned int cur = rr->current;
  35.     cur = cur * MUL % MOD + INC % MOD;
  36.     rr->current = cur;
  37.     return cur;
  38. }
  39.  
  40. static void destroy(RandomGenerator *rr)
  41. {
  42.     if (rr == NULL) {
  43.         return;
  44.     }
  45.     free(rr);
  46. }
  47.  
  48. RandomGenerator *random_create(int seed)
  49. {
  50.     RandomGenerator *rr = calloc(1, sizeof(*rr));
  51.     if (rr == NULL) {
  52.         return NULL;
  53.     }
  54.     rr->current = seed;
  55.     rr->ops = &ops;
  56.     return rr;
  57. }
Advertisement
RAW Paste Data Copied
Advertisement