Game Development Community

dev|Pro Game Development Curriculum

A Utility Random Class

by Saurav Mohapatra · 05/27/2003 (9:30 am) · 1 comments

Download Code File

/*
  *****************************************************************
			CRandom - A Utility Random Class 
			written by Saurav Mohapatra
			standard_template@yahoo.com

			This software is provided as is without any warranty
			You can use it in any software as long as:
				+ I get prominent credit in the doc or the source comments (
					(You can copy paste this notice)
				+ you do not blame me for any damage it causes :)


  *****************************************************************	
*/
#pragma warning(disable : 4786)

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <list>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <ctime>
#include <cmath>


//
//	using directives
//
using std::string;
using std::vector;
using std::map;
using std::list;

using std::istream;
using std::ostream;
using std::ifstream;
using std::ofstream;

using std::cout;
using std::cerr;
using std::cin;
using std::endl;
using std::ios;

//
//	handy typedefs
//
typedef unsigned char	byte;
typedef unsigned short	uint16;
typedef short			int16;
typedef unsigned long	ulong;
typedef long			int32;
typedef ulong			uint32;





class CRandomGen
{
	friend class CRandom;
private:
	static void init();
	static void deinit();
	static long nextRandom();

	static bool m_initDone;
	static long m_initCount;
};

class CRandom
{
public:
	CRandom(){ CRandomGen::init(); }
	virtual ~CRandom(){ CRandomGen::deinit(); }

	double nextDouble(double first=0.00,double second=1.00);
	ulong  nextLong(ulong first=0L,ulong second=RAND_MAX);
	bool   nextBool();


	

};

using namespace std;
bool CRandomGen::m_initDone = false;
long CRandomGen::m_initCount = 0;
double CRandom::nextDouble(double first,double second)
{
	if(first == second)
	{
		return first;
	}
	else if(first > second)
	{
		return nextDouble(second,first);
	}
	else
	{
		double diff = second - first;
		double ratio = (double)rand()/(double)RAND_MAX;

		return first + diff * ratio;
	}
}
ulong  CRandom::nextLong(ulong first,ulong second)
{
	return (ulong)nextDouble((double)first,(double)second);
}
bool   CRandom::nextBool()
{
	return nextDouble(0.00,1.00) >= 0.5;
}

void CRandomGen::init()
{
	if(m_initCount == 0)
	{
		srand(time(0));
	}
	m_initCount++;
}
void CRandomGen::deinit()
{
	m_initCount--;
	if(m_initCount == 0)
	{
		srand(1);
	}
}
long CRandomGen::nextRandom()
{
	return rand();
}


int main(int argc,char **argv)
{
	CRandom r;
	cout<<"Next Double : "<<r.nextDouble()<<endl;
	cout<<"Next Double (100 - 200) : "<<r.nextDouble(100.0,200.00)<<endl;

	cout<<"Next Boolean : "<<(r.nextBool()?"true":"false")<<endl;
	return 0;
}

#1
06/01/2003 (5:41 pm)
yea ..
and then when your ready..
you can go here www.math.keio.ac.jp/~matumoto/emt.html and play with that one :)