CPP   33

IntBag.cpp

Guest on 5th August 2022 01:31:47 AM

  1. #include "stdstuff.h"
  2.  
  3. #include "IntBag.h"
  4.  
  5. // note that the constructor and size are not mentioned here as their
  6. // implementations are completely specified in the header file
  7.  
  8.  
  9. // adds a value to the bag.  returns true on success (space available)
  10. // and false on failure (bag full)
  11. bool IntBag::add (int value) {
  12.  
  13.   if (count == MAXVALUES) return false;
  14.  
  15.   data[count++] = value;
  16.   walkInProgress = false; // scrub any ongoing walk
  17.   return true;
  18.  
  19. }
  20.  
  21.  
  22. // removes one occurance of the specfied value from the bag.  returns
  23. // true on success (value existed) and false on failure (value did not exist)
  24. bool IntBag::remove (int value) {
  25.  
  26.   int i;
  27.  
  28.   for (i = 0; i < count; i++) {
  29.     if (data[i] == value) {
  30.       // we've found the data value.
  31.       // overwrite it with the last data value and adjust the count
  32.       // to reflect the fact that there are now one fewer values in
  33.       // the bag.  note that this works even if the value being removed
  34.       // is the last value in the bag.
  35.       data[i] = data[--count];
  36.       walkInProgress = false; // scrub any ongoing walk
  37.       return true;
  38.     }
  39.   }
  40.  
  41.   return false;
  42.  
  43. }
  44.  
  45.  
  46. // returns the number of times that the specified value occurs in the bag
  47. int IntBag::countOccurrences (int value) const {
  48.  
  49.   int i, occurrences = 0;
  50.  
  51.   for (i = 0; i < count; i++) {
  52.     if (data[i] == value) {
  53.       occurrences++;
  54.     }
  55.   }
  56.  
  57.   return occurrences;
  58.  
  59. }
  60.  
  61.  
  62. bool IntBag::startWalk (int &value) {
  63.  
  64.   if (count == 0) return false;
  65.  
  66.   walkInProgress = true; walkPosition = 0;
  67.   value = data[walkPosition];
  68.   return true;
  69.  
  70. }
  71.  
  72.  
  73. bool IntBag::continueWalk (int &value) {
  74.  
  75.   if (!walkInProgress) {
  76.     throw range_error ("IntBag::continueWalk invalid call");
  77.   }
  78.   if (++walkPosition == count) {
  79.     walkInProgress = false; // we've come to the end of the road
  80.     return false;
  81.   }
  82.   value = data[walkPosition];
  83.   return true;
  84.  
  85. }
  86.  
  87.  
  88. // randomly picks and returns one of the values in the bag.
  89. // throws a range_error exception if the bag is empty.
  90. int IntBag::pickRandom () const {
  91.  
  92.   int i;
  93.  
  94.   if (count == 0) {
  95.     throw range_error ("IntBag::pickRandom bag is empty");
  96.   }
  97.  
  98.   i = (int) ((rand () / (RAND_MAX + 1.0)) * count);
  99.   return data[i];
  100.  
  101. }

Raw Paste


Login or Register to edit or fork this paste. It's free.