Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. /*
  2. * This program takes a sample of the specified size (SIZE_OF_SAMPLES)
  3. * from integers between 0 and a MAX value (ends inclusive) without
  4. * replacement. Contains bugs to practice debugging.
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. #define MAX 6
  11. #define SIZE_OF_SAMPLES 3
  12. #define REP 5
  13.  
  14. int MemberQ(int *array, int arrSize, int x);
  15. void UniqRandInts(int max, int howmany, int * resultPtr);
  16.  
  17. int main(void) {
  18. int arr[SIZE_OF_SAMPLES], i, j, max, size;
  19.  
  20. srand(9808);
  21. max = MAX;
  22. size = SIZE_OF_SAMPLES;
  23.  
  24. for (i = 0; i < REP; i++) {
  25. UniqRandInts(max, size, arr);
  26. for(j = 0; j < size; j++) {
  27. printf("%d ", arr[j]);//swap arr[i] with arr[j]
  28. }
  29. printf("\n");
  30. }
  31. return 0;
  32. }
  33.  
  34. /*
  35. * resultPtr[] will be initialized with a sample of the specified size
  36. * (n) from integers between 0 and a max value (ends inclusive)
  37. * without replacement.
  38. */
  39. void UniqRandInts(int max, int n, int *resultPtr) {
  40. int cntr = 0, r;
  41.  
  42. while(cntr < n) {
  43. r = rand();
  44. r = r % (max + 1);
  45. if (MemberQ(resultPtr, cntr, r)) {
  46. resultPtr[cntr] = r;
  47. cntr++;
  48. }
  49. }
  50. return;
  51. }
  52.  
  53. /*
  54. * Check if an integer x is included in array[] of arrSize.
  55. * Returns: 1 if x is a member
  56. * 0 if x is not a member
  57. */
  58. int MemberQ(int *array, int arrSize, int x) {
  59. int i;
  60.  
  61. for (i = 0; i < arrSize; i++) {
  62. if (array[i] == x) {
  63. return 0;//not a member should be 0 instead of 1
  64. }
  65. }
  66. return 1;//return 1 because it is a member
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement