- #include "stdstuff.h"
- #include "IntBag.h"
- // note that the constructor and size are not mentioned here as their
- // implementations are completely specified in the header file
- // adds a value to the bag. returns true on success (space available)
- // and false on failure (bag full)
- bool IntBag::add (int value) {
- if (count == MAXVALUES) return false;
- data[count++] = value;
- walkInProgress = false; // scrub any ongoing walk
- return true;
- }
- // removes one occurance of the specfied value from the bag. returns
- // true on success (value existed) and false on failure (value did not exist)
- bool IntBag::remove (int value) {
- int i;
- for (i = 0; i < count; i++) {
- if (data[i] == value) {
- // we've found the data value.
- // overwrite it with the last data value and adjust the count
- // to reflect the fact that there are now one fewer values in
- // the bag. note that this works even if the value being removed
- // is the last value in the bag.
- data[i] = data[--count];
- walkInProgress = false; // scrub any ongoing walk
- return true;
- }
- }
- return false;
- }
- // returns the number of times that the specified value occurs in the bag
- int IntBag::countOccurrences (int value) const {
- int i, occurrences = 0;
- for (i = 0; i < count; i++) {
- if (data[i] == value) {
- occurrences++;
- }
- }
- return occurrences;
- }
- bool IntBag::startWalk (int &value) {
- if (count == 0) return false;
- walkInProgress = true; walkPosition = 0;
- value = data[walkPosition];
- return true;
- }
- bool IntBag::continueWalk (int &value) {
- if (!walkInProgress) {
- throw range_error ("IntBag::continueWalk invalid call");
- }
- if (++walkPosition == count) {
- walkInProgress = false; // we've come to the end of the road
- return false;
- }
- value = data[walkPosition];
- return true;
- }
- // randomly picks and returns one of the values in the bag.
- // throws a range_error exception if the bag is empty.
- int IntBag::pickRandom () const {
- int i;
- if (count == 0) {
- throw range_error ("IntBag::pickRandom bag is empty");
- }
- i = (int) ((rand () / (RAND_MAX + 1.0)) * count);
- return data[i];
- }