// implementation file randgen.cpp
// adapted from Astrachan, "A Computer Science Tapestry", 2nd edition,
//    McGraw Hill, pp. 214, 217? (not sure of these pg numbers)

#include <time.h>                // for time()
#include <stdlib.h>              // for rand/srand
#include "randgen.h"
#include <cmath>
using namespace std;

int RandGen::ourInitialized = 0;

// SetSeed
// postcondition: system srand() used to initialize seed
//                once per program (this is a static function)    

void RandGen::SetSeed(int seed)
{
   if (0 == ourInitialized)
   {   
      ourInitialized = 1;   // only call srand once
      srand(seed);          // randomize
   }
}

// RandGen  
// postcondition: system srand() used to initialize seed
//                once per program     

RandGen::RandGen()
{
   if (0 == ourInitialized)
   {   
      ourInitialized = 1;          // only call srand once
      srand(unsigned(time(0)));    // randomize
   }
}

// RandInt (1 argument version)
// precondition: max > 0
// postcondition: returns int in [0..max)     

int RandGen::RandInt(int max)
{  
   return int(RandReal() * max);
}

// RandInt (2 argument version)
// precondition: low <= max     
// postcondition: returns int in [low..max]     

int RandGen::RandInt(int low, int max)
{ 
   return low + RandInt(max-low+1);
}

// RandReal (1 argument version)
// postcondition: returns double in [0..1)     

double RandGen::RandReal()
{     
   return rand() / (double(RAND_MAX) + 1); 
}

// RandReal (2 argument version)

double RandGen::RandReal(double low, double high)
{
   double width = fabs(high-low);
   double thelow = low < high ? low : high;
   return RandReal()*width + thelow;
}