Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1.  
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <errno.h>
  5. #define DEFAULT_SIZE //הגודל ברירת מחדל שאת רוצה
  6. static size_t uniques_size;
  7. static int* uniques_arr;
  8. static bool uniques_initialized=false;
  9.  
  10. void initialize_uniques(size_t size, int seed)
  11. {
  12. if (unqiues_initialized)
  13. unique_arr=realloc(unique_arr, sizeof(int)*size);
  14. else uniques_arr=calloc(size, sizeof(int));
  15. if (uniques_arr==NULL)
  16. {
  17. errno=ENOMEM;
  18. unique_initialized=false; //in case of reinitialization
  19. return;
  20. }
  21. srand(seed);
  22. for (int i=0; i<size; i++)
  23. uniques_arr[i] = i;
  24. uniques_initialized=true;
  25. }
  26.  
  27. void int_swap(int* a, int* b)
  28. {
  29. int temp=*a;
  30. *a=*b;
  31. *b=temp;
  32. }
  33. int generate_unique()
  34. {
  35. if (!unique_initialized||uniques_size==0)
  36. initialize_uniques(DEFAULT_SIZE, time(NULL)) ;
  37. swap(uniques_arr[rand()%uniques_size-1], uniques_arr[uniques_size-1]);
  38. uniques_size--;
  39. return uniques_arr[uniques_size] ;
  40. }
  41.  
  42.  
  43. int uniques_left()
  44. {
  45. return uniques_size;
  46. }
  47.  
  48. ואת יכולה להפיץ בheader רק את uniques_left, generate_uniques וinitialize_uniques ככה שלא יהיו משתנים גלובליים חשופים
  49.  
  50. ואז תוכלי להשתמש בזה ככה
  51. initialize_uniques(4, time(NULL));
  52. if (errno==ENOMEM)
  53. abort();
  54. int arr[4];
  55. for (int i=0; i<4, i++)
  56. arr[i]=generate_uniques();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement