Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct RandomGenerator {
- struct RandomOperations *ops;
- int seed;
- int a;
- int c;
- int m;
- } RandomGenerator;
- typedef struct RandomOperations {
- void (*destroy)(RandomGenerator *);
- int (*next)(RandomGenerator *);
- } RandomOperations;
- int next(RandomGenerator *rr) {
- int res = (rr->a * rr->seed + rr->c) % rr->m;
- rr->seed = res;
- return res;
- }
- void destroy(RandomGenerator *rr) {
- free(rr->ops);
- free(rr);
- }
- RandomGenerator *random_create(int seed) {
- RandomGenerator *rr = (RandomGenerator *)malloc(sizeof(RandomGenerator));
- rr->ops = (RandomOperations *)malloc(sizeof(RandomOperations));
- rr->ops->next = &next;
- rr->ops->destroy = &destroy;
- rr->seed = seed;
- rr->a = 1103515245;
- rr->c = 12345;
- rr->m = 1 << 31;
- return rr;
- }
- int main(void) {
- RandomGenerator *rr = random_create(1234);
- for (int j = 0; j < 100; ++j) {
- printf("%d\n", rr->ops->next(rr));
- }
- rr->ops->destroy(rr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement