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

  1. //: C21:Generators.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. // Different ways to fill sequences
  7. #ifndef GENERATORS_H
  8. #define GENERATORS_H
  9. #include <set>
  10. #include <cstdlib>
  11. #include <cstring>
  12. #include <ctime>
  13.  
  14. // A generator that can skip over numbers:
  15. class SkipGen {
  16.   int i;
  17.   int skp;
  18. public:
  19.   SkipGen(int start = 0, int skip = 1)
  20.     : i(start), skp(skip) {}
  21.   int operator()() {
  22.     int r = i;
  23.     i += skp;
  24.     return r;
  25.   }
  26. };
  27.  
  28. // Generate unique random numbers from 0 to mod:
  29. class URandGen {
  30.   std::set<int> used;
  31.   int modulus;
  32. public:
  33.   URandGen(int mod) : modulus(mod) { 
  34.     std::srand(std::time(0)); 
  35.   }
  36.   int operator()() {
  37.     while(true) {
  38.       int i = (int)std::rand() % modulus;
  39.       if(used.find(i) == used.end()) {
  40.         used.insert(i);
  41.         return i;
  42.       }
  43.     }
  44.   }
  45. };
  46.  
  47. // Produces random characters:
  48. class CharGen {
  49.   static const char* source;
  50.   static const int len;
  51. public:
  52.   CharGen() { std::srand(std::time(0)); }
  53.   char operator()() { 
  54.     return source[std::rand() % len];
  55.   }
  56. };
  57.  
  58. // Statics created here for convenience, but
  59. // will cause problems if multiply included:
  60. const char* CharGen::source = "ABCDEFGHIJK"
  61.   "LMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  62. const int CharGen::len = std::strlen(source);
  63. #endif // GENERATORS_H ///:~
  64.