Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <time.h>
- #include <errno.h>
- #define DEFAULT_SIZE //הגודל ברירת מחדל שאת רוצה
- static size_t uniques_size;
- static int* uniques_arr;
- static bool uniques_initialized=false;
- void initialize_uniques(size_t size, int seed)
- {
- if (unqiues_initialized)
- unique_arr=realloc(unique_arr, sizeof(int)*size);
- else uniques_arr=calloc(size, sizeof(int));
- if (uniques_arr==NULL)
- {
- errno=ENOMEM;
- unique_initialized=false; //in case of reinitialization
- return;
- }
- srand(seed);
- for (int i=0; i<size; i++)
- uniques_arr[i] = i;
- uniques_initialized=true;
- }
- void int_swap(int* a, int* b)
- {
- int temp=*a;
- *a=*b;
- *b=temp;
- }
- int generate_unique()
- {
- if (!unique_initialized||uniques_size==0)
- initialize_uniques(DEFAULT_SIZE, time(NULL)) ;
- swap(uniques_arr[rand()%uniques_size-1], uniques_arr[uniques_size-1]);
- uniques_size--;
- return uniques_arr[uniques_size] ;
- }
- int uniques_left()
- {
- return uniques_size;
- }
- ואת יכולה להפיץ בheader רק את uniques_left, generate_uniques וinitialize_uniques ככה שלא יהיו משתנים גלובליים חשופים
- ואז תוכלי להשתמש בזה ככה
- initialize_uniques(4, time(NULL));
- if (errno==ENOMEM)
- abort();
- int arr[4];
- for (int i=0; i<4, i++)
- arr[i]=generate_uniques();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement