6
Random
- #include <climits>
- #include <ctime>
- #include <iostream>
- #ifdef DEBUG
- int debug = 1; // 0 - off, 1 - on
- #endif
- #ifdef DEBUG
- #define ONDEBUG( expr ) do { if ( debug ) { expr; } } while ( 0 )
- #else
- #define ONDEBUG( expr )
- #endif
- const unsigned long RANDOM_MULT = 234567821;
- class Random {
- public:
- Random( ) { _seed = time( 0 ); };
- Random( unsigned long seed ) : _seed( seed ) { randomize(); };
- int integer( int max = INT_MAX )
- {
- randomize();
- return _seed % INT_MAX;
- }
- int integer( int min, int max )
- {
- randomize();
- return min + _seed % (max - min + 1);
- };
- double real( )
- {
- randomize();
- return double( _seed ) / double( ULONG_MAX );
- }
- private:
- unsigned long _seed;
- void randomize( )
- {
- _seed = (RANDOM_MULT * _seed + 1) % ULONG_MAX;
- ONDEBUG( std::cout << "_seed=" << _seed << std::endl; );
- };
- };
- #if defined( STANDALONE )
- int main() {
- Random r;
- ONDEBUG( std::cout << "RANDOM_MULT=" << RANDOM_MULT << std::endl; );
- for( int i = 0; i <= 10; i++ )
- {
- int x = r.integer();
- int y = r.integer( 1, 99 );
- double f = r.real();
- std::cout << "\t" << x << "\t"<< y << "\t" << f << std::endl;
- }
- exit( 0 );
- }
- #endif
Commentaires