The_Law

Untitled

Nov 5th, 2018
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.87 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. enum
  5. {
  6.     MULTIPLY = 1103515245,
  7.     INCREMENT = 12345,
  8.     MODULE = (1ll << 31)
  9. };
  10.  
  11. typedef struct RandomGenerator
  12. {
  13.     struct RandomOperations *ops;
  14.     unsigned res;
  15. } RandomGenerator;
  16.  
  17. void
  18. destroy(RandomGenerator *rr)
  19. {
  20.     free(rr->ops);
  21.     free(rr);
  22. }
  23.  
  24. unsigned
  25. next(RandomGenerator *rr)
  26. {
  27.     return (rr->res * MULTIPLY + INCREMENT) & (MODULE - 1);
  28. }
  29.  
  30. struct RandomOperations
  31. {
  32.     unsigned (*next)(RandomGenerator *rr);
  33.     void (*destroy)(RandomGenerator *rr);
  34. };
  35.  
  36. RandomGenerator *
  37. random_create(int seed)
  38. {
  39.     RandomGenerator *rr = malloc(sizeof(*rr));
  40.     if (rr == NULL) {
  41.         exit(1);
  42.     }
  43.     rr->ops = malloc(sizeof(*(rr->ops)));
  44.     if (rr->ops == NULL) {
  45.         exit(1);
  46.     }
  47.     rr->ops->next = &next;
  48.     rr->ops->destroy = &destroy;
  49.     rr->res = seed;
  50.     return rr;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment