Advertisement
_takumi

random-ops-3

Jan 20th, 2023
938
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.06 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct RandomGenerator {
  5.     struct RandomOperations *ops;
  6.     int seed;
  7.     int a;
  8.     int c;
  9.     int m;
  10. } RandomGenerator;
  11.  
  12. typedef struct RandomOperations {
  13.     void (*destroy)(RandomGenerator *);
  14.     int (*next)(RandomGenerator *);
  15. } RandomOperations;
  16.  
  17. int next(RandomGenerator *rr) {
  18.     int res = (rr->a * rr->seed + rr->c) % rr->m;
  19.     rr->seed = res;
  20.     return res;
  21. }
  22.  
  23. void destroy(RandomGenerator *rr) {
  24.     free(rr->ops);
  25.     free(rr);
  26. }
  27.  
  28. RandomGenerator *random_create(int seed) {
  29.     RandomGenerator *rr = (RandomGenerator *)malloc(sizeof(RandomGenerator));
  30.     rr->ops = (RandomOperations *)malloc(sizeof(RandomOperations));
  31.     rr->ops->next = &next;
  32.     rr->ops->destroy = &destroy;
  33.     rr->seed = seed;
  34.     rr->a = 1103515245;
  35.     rr->c = 12345;
  36.     rr->m = 1 << 31;
  37.     return rr;
  38. }
  39.  
  40. int main(void) {
  41.     RandomGenerator *rr = random_create(1234);
  42.     for (int j = 0; j < 100; ++j) {
  43.         printf("%d\n", rr->ops->next(rr));
  44.     }
  45.     rr->ops->destroy(rr);
  46.     return 0;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement