Random.h
Code: Select all
#ifndef RandomH
#define RandomH
// =====================================================
// (C) 2012 Reinhard Scharnagl, 80992 Munich, Germany
// -----------------------------------------------------
// 32 Bit Pseudo Random Number Generator
// -----------------------------------------------------
// Assumption: datatype "unsigned" is having 32 bits
// =====================================================
class Random {
private:
// Seed (buffer for creating follow-up numbers)
unsigned m_Seed;
public:
// constructor (randomizing)
Random(void);
// reset generator to a new starting point
void __fastcall setSeed(unsigned newSeed);
// create a starting point randomized by time
unsigned __fastcall randomize(void);
// create a following-up random number
unsigned __fastcall rand(void);
// create a 0-1-bit balanced random Zobrist key
unsigned __fastcall rand01(void);
// create a random number below a given limit > 0
unsigned __fastcall rangedRand(unsigned limit);
};
#endif /* #ifndef RandomH */Code: Select all
#include <limits.h>
#include <time.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "Random.h"
// constructor (randomizing)
Random::Random(void) {
// initially randomize by time
randomize();
}
// reset generator to a new starting point
void __fastcall Random::setSeed(unsigned newSeed) {
// store new seed
m_Seed = newSeed;
}
// create a starting point randomized by time
unsigned __fastcall Random::randomize(void) {
// combining time and status quo of the seed
return m_Seed = rand() * (unsigned)time(0L);
}
// create a following-up random number
unsigned __fastcall Random::rand(void) {
// create by two selected prime numbers and store
return m_Seed = m_Seed * 87641 + 98731;
}
// create a 0-1-bit balanced random Zobrist key
unsigned __fastcall Random::rand01(void) {
// Zobrist key candidate and its copy
unsigned answer, answScan;
// bit down-counter
unsigned bitCountDown;
// select next qualified Zobrist number
do {
// create new candidate
answScan = answer = rand();
// load intended bit count into down-counter
bitCountDown = 2 * CHAR_BIT;
// analyze 1-bits of current candidate
while (answScan) {
// register lowest 1-bit
--bitCountDown;
// clear lowest 1-bit
answScan &= answScan - 1;
}
// while unbalanced
} while (bitCountDown);
// found qualified Zobrist key
return answer;
}
// create a random number below a given limit > 0
unsigned __fastcall Random::rangedRand(unsigned limit) {
// set a top limit for securing equal distribution
unsigned topLimit = UINT_MAX - UINT_MAX % limit;
// number candidate
unsigned value;
// create next random number below that top limit
do {
value = rand();
} while (value >= topLimit);
// apply modulo to result
return value % limit;
}