Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. #include <iostream>
  2. #include <ostream>
  3. #include <string>
  4. #include <time.h>
  5.  
  6. using namespace std; // allows unqualified use of identifiers of namespace std
  7.  
  8. class Singleton
  9. {
  10.     private:
  11.     /* Here will be the instance stored. */
  12.     static Singleton* instance;
  13.  
  14.     /* Private constructor to prevent instancing. */
  15.     Singleton();
  16.    
  17.     int max;
  18.     int factor;
  19.     int increment;
  20.     unsigned long int actualrandom;
  21.    
  22.     public:
  23.     /* Static access method. */
  24.     static Singleton* getInstance();
  25.    
  26.     bool ask_yn(const char * msg);
  27.        
  28.     void random_number();
  29.            
  30.     void random_seed();
  31. };
  32.  
  33. /* Null, because instance will be initialized on demand. */
  34. Singleton* Singleton::instance = 0;
  35.  
  36. Singleton* Singleton::getInstance()
  37. {
  38.     if (instance == 0)
  39.     {
  40.         instance = new Singleton();
  41.     }
  42.  
  43.     return instance;
  44. }
  45.  
  46. Singleton::Singleton(){
  47.     this->max=1000;
  48.     this->factor=623;
  49.     this->increment=525;
  50.     this->actualrandom=((this->factor*157)+this->increment)%this->max;
  51. }
  52.  
  53.  
  54. bool Singleton::ask_yn(const char * msg) {
  55.     cout << msg << " (y/n)? " << flush;
  56.     char answer;
  57.     cin >> answer;
  58.     if (answer == 'y' || answer == 'Y')
  59.         return true;
  60.     else return false;
  61.     }
  62.  
  63. void Singleton::random_number() {
  64.     this->actualrandom = ((this->factor * this->actualrandom) + this->increment) % this->max;
  65.     cout<<this->actualrandom<<"\n";
  66. }
  67.  
  68. void Singleton::random_seed(){
  69.     time_t timer;
  70.     time(&timer);
  71.     // timer*100 gives negative number
  72.     this->actualrandom= timer%this->max;
  73. }
  74.  
  75. int main(){
  76.     //new Singleton(); // Won't work
  77.     Singleton* s = Singleton::getInstance(); // Ok
  78.    
  79.     if(s->ask_yn("Random seed the generator")==true){
  80.         s->random_seed();
  81.     }
  82.    
  83.     do{
  84.         s->random_number();
  85.     }while(s->ask_yn("Another random number?"));
  86.    
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement