Grafalgo
Library of useful data structures and algorithms
|
00001 00009 #ifndef UTIL_H 00010 #define UTIL_H 00011 00012 #include "stdinc.h" 00013 00014 using namespace std; 00015 00016 namespace grafalgo { 00017 00020 class Util { 00021 public: 00022 static const int32_t BIGINT32 = 0x7ffffff; 00023 00024 // basic input helper functions 00025 static bool skipSpace(istream& in, bool=false); 00026 static bool skipBlank(istream& in); 00027 static bool readWord(istream&, string&, bool= false); 00028 static bool readInt(istream&, int&, bool= false); 00029 static bool verify(istream&, char c, bool=false); 00030 00031 // other stuff 00032 static bool prefix(string&, string&); 00033 static int strnlen(char*, int); 00034 static void genPerm(int, int*); 00035 static uint32_t getTime(); 00036 static void warning(const string&); 00037 static void fatal(const string&); 00038 00039 // convenience functions for random number generation 00040 // Should eventually replace with C++11 <random> variants 00041 static double randfrac(); 00042 static int randint(int, int); 00043 static double randexp(double); 00044 static int randgeo(double); 00045 static int randTruncGeo(double, int); 00046 static double randpar(double, double); 00047 }; 00048 00049 inline void Util::warning(const string& msg) { 00050 cerr << "Warning: " << msg << endl; 00051 } 00052 00053 inline void Util::fatal(const string& msg) { 00054 cerr << "Fatal: " << msg << endl; 00055 if (errno != 0) perror(""); 00056 exit(1); 00057 } 00058 00059 00063 inline double Util:: randfrac() { return ((double) random())/BIGINT32; } 00064 00071 inline int Util::randint(int lo, int hi) { 00072 return lo + (random() % (hi + 1 - lo)); 00073 } 00074 00075 // Return a random number from an exponential distribution with mean mu 00076 inline double Util::randexp(double mu) { return -mu*log(randfrac()); } 00077 00082 inline int Util::randgeo(double p) { 00083 return p > .999999 ? 1 : 00084 max(1,int(.999999 +log(randfrac())/log(1-p))); 00085 } 00086 00090 inline int Util::randTruncGeo(double p, int k) { 00091 double x = 1 - exp((k-1)*log(1-p)); 00092 int r = int(.999999+log(randfrac()/x)/log(1-p)); 00093 return p > .999999 ? 1 : max(1,min(r,k)); 00094 } 00095 00099 inline double Util::randpar(double mu, double s) { 00100 return mu*(1-1/s)/exp((1/s)*log(randfrac())); 00101 } 00102 00103 } // ends namespace 00104 00105 #endif