00001 #ifndef Impala_Util_Random_h
00002 #define Impala_Util_Random_h
00003
00004 #include "Basis/ILog.h"
00005 #include <ctime>
00006 #include <cstdlib>
00007
00008 namespace Impala
00009 {
00010 namespace Util
00011 {
00012
00018 static void
00019 SetRandomSeed(int seed)
00020 {
00021 std::srand(seed);
00022 }
00023
00024 static void
00025 RandomiseSeed()
00026 {
00027 SetRandomSeed(time(0));
00028 }
00029
00036 int
00037 RandomInt(int upperBound)
00038 {
00039 ILOG_VAR(Impala.Util.Random.RandomInt);
00040 if(upperBound > RAND_MAX)
00041 ILOG_WARNING(upperBound <<" upperBound > RAND_MAX "<< RAND_MAX);
00042 return (int) (((double) std::rand() / ((double) RAND_MAX + 1.0)) *
00043 upperBound);
00044 }
00045
00046 int
00047 RandomInt()
00048 {
00049 return RandomInt(RAND_MAX);
00050 }
00051
00053 double
00054 RandomDouble(double upperBound)
00055 {
00056 ILOG_VAR(Impala.Util.Random.RandomDouble);
00057 if(upperBound > RAND_MAX)
00058 ILOG_WARNING(upperBound <<" upperBound > RAND_MAX");
00059 return (double) (((double) std::rand() / ((double) RAND_MAX + 1.0)) *
00060 upperBound);
00061 }
00062
00063 double
00064 RandomDouble()
00065 {
00066 return RandomDouble(1.);
00067 }
00068
00070 std::set<int>
00071 RandomUniqueNumbers(int count, int upperBound)
00072 {
00073 ILOG_VAR(Impala.Util.Random.RandomUniqueNumbers);
00074 std::set<int> set;
00075 if(count > upperBound)
00076 {
00077 ILOG_ERROR("count > upperBound:"<< count <<" "<< upperBound);
00078 return set;
00079 }
00080 if(count > RAND_MAX)
00081 {
00082 ILOG_ERROR("count > RAND_MAX:"<< count <<" "<< RAND_MAX);
00083 return set;
00084 }
00085 while(set.size() < count)
00086 {
00087 int draw = RandomInt(upperBound);
00088 if(set.find(draw) == set.end())
00089 set.insert(draw);
00090 }
00091 return set;
00092 }
00093
00094 void
00095 DumpRandomSequence(int seed, int length, int maxint)
00096 {
00097 std::ofstream ofs("randomdump.txt");
00098 if(!ofs.is_open())
00099 return;
00100 ofs << length <<" random numbers below "<< maxint << ", seed == "<< seed <<"\n";
00101 Util::SetRandomSeed(seed);
00102 for(int i=0 ; i<length ; ++i)
00103 ofs << Util::RandomInt(maxint) << ((i%20==19)?"\n":" ");
00104 }
00105
00106 }
00107 }
00108
00109 #endif