00001 #ifndef DV_UTIL_RANDOM_H 00002 #define DV_UTIL_RANDOM_H 00003 // $Id: random.h,v 1.7 2008/07/17 18:12:52 dvermeir Exp $ 00004 00005 #include <stdexcept> 00006 00007 namespace Dv { 00008 namespace Util { 00009 /** Class supporting random number generation using /dev/urandom 00010 * Example usage 00011 * @code 00012 * unsigned long key = Dv::Util::Random::rand(); 00013 * @endcode 00014 */ 00015 class Random { 00016 public: 00017 /** Produces a random unsigned long taken from /dev/urandom. 00018 * An exception is thrown if anything goes wrong, e.g. 00019 * the file /dev/urandom cannot be opened. 00020 * 00021 * Should probably automatically switch to another 00022 * implementation if /dev/urandom is not available. 00023 * This is probably a naive approach but will do for 00024 * the simple purposes it is used for. 00025 */ 00026 static unsigned long rand() throw (std::runtime_error); 00027 00028 /** Gamble such that the chance of 'true' is N out of M. 00029 * E.f. %a gamble(15,100) will return true in 15% of the 00030 * cases. 00031 * @param chances N in probablity N/M 00032 * @param out_of M in probablity N/M 00033 * @return true with chances/out_of probability 00034 */ 00035 static bool gamble(size_t chances, size_t out_of ) throw (std::runtime_error) { 00036 if (chances >= out_of) 00037 return true; 00038 return (( rand() % out_of ) < chances ); 00039 } 00040 00041 /** Pick a number out of a range. 00042 * @param min of range @a [min..max[ 00043 * @param max of range @a [min..max[ 00044 * @return 'random' number out of @a [min..max[ 00045 * @exception if min > max 00046 */ 00047 static size_t pick_one(size_t min, size_t max) throw (std::runtime_error); 00048 00049 }; 00050 } 00051 } 00052 #endif
dvutil-1.0.10 | [ 5 December, 2009] |