home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C19 / Urand.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.0 KB  |  43 lines

  1. //: C19:Urand.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Unique random number generator
  7. #ifndef URAND_H
  8. #define URAND_H
  9. #include <cstdlib>
  10. #include <ctime>
  11.  
  12. template<int upperBound>
  13. class Urand {
  14.   int used[upperBound];
  15.   bool recycle;
  16. public:
  17.   Urand(bool recycle = false);
  18.   int operator()(); // The "generator" function
  19. };
  20.  
  21. template<int upperBound>
  22. Urand<upperBound>::Urand(bool recyc) 
  23.   : recycle(recyc) {
  24.   memset(used, 0, upperBound * sizeof(int));
  25.   srand(time(0)); // Seed random number generator
  26. }
  27.  
  28. template<int upperBound>
  29. int Urand<upperBound>::operator()() {
  30.   if(!memchr(used, 0, upperBound)) {
  31.     if(recycle)
  32.       memset(used,0,sizeof(used) * sizeof(int));
  33.     else
  34.       return -1; // No more spaces left
  35.   }
  36.   int newval;
  37.   while(used[newval = rand() % upperBound])
  38.     ; // Until unique value is found
  39.   used[newval]++; // Set flag
  40.   return newval;
  41. }
  42. #endif // URAND_H ///:~
  43.