Random number functions

mrnutty 0 Tallied Votes 291 Views Share

Random number generator under its own namespace.

Its a sample program.

#include<ctime> 
#include<iostream>
#include<string>

using std::string;
using std::cout;
using std::endl;

namespace Random
{

	//returns a random number ranged from :
	//0 -> max
	long Rand(int max = 100) { return rand() * max/RAND_MAX; }
	// long (min->max)
	long Randi(int min, int max){
		return long ( 0.5f + ((float)rand()/0x7fff * (max-min) + min) );
	}
	// float (min - > max)
	float Randf(int min, int max){
		return ( 0.1f + (float)rand()/0x7fff  )* (max-min) + min;
	}
	//double ( min -> max )
	double RandD(int min, int max){
		return (0.1f + (double)rand()/0x7fff ) * (max-min) + min;
	}
	// char a - > z
	char RandLowChar() {
		return rand() % ( int('z') - int('a') ) + int('a');
	}
	// char ( A - > Z)
	char RandHighChar(){
		return rand() % ( int('Z') - int('A') ) + int('A');
	}
	// random lowered cased string
	string RandLowStr(int len){
		string str;		
		while(len--) str += RandLowChar();
		return str;
	}
	// random uppered case string
	string RandHighStr(int len){
		string str;		
		while(len--) str += RandHighChar();
		return str;
	}
}

int main()
{	

	for(int i = 0; i != 100; i++)
	{
		if(!(i%10) ) cout<<endl;

		cout.width(5);
		cout<<Random::Randi(-100,100)<<" ";
	}

	cout<<endl<<endl;

	for(int i = 0; i != 100; i++)
	{
		if(!(i%10) ) cout<<endl;

		cout.width(8);
		cout.precision(2);
		cout<<Random::Randf(-1,1)<<" ";
	}

	cout<<endl<<endl;

	for(int i = 0; i != 100; i++)
	{
		if(!(i%10) ) cout<<endl;
		cout.width(8);
		cout<<Random::RandHighStr(5)<<" ";
	}

	cout<<endl<<endl;

	for(int i = 0; i != 100; i++)
	{
		if(!(i%10) ) cout<<endl;
		cout.width(8);
		cout<<Random::RandLowStr(5)<<" ";
	}

	cout<<endl<<endl;
	return 0;
}