6

Random

  1. #include <climits>
  2. #include <ctime>
  3.  
  4. #include <iostream>
  5.  
  6. #ifdef DEBUG
  7. int debug = 1;  // 0 - off, 1 - on
  8. #endif
  9.  
  10. #ifdef DEBUG
  11. #define ONDEBUG( expr ) do { if ( debug ) { expr; } } while ( 0 )
  12. #else
  13. #define ONDEBUG( expr )
  14. #endif
  15.  
  16. const unsigned long RANDOM_MULT = 234567821;
  17.  
  18. class Random {
  19. public:
  20.     Random( ) { _seed = time( 0 ); };
  21.     Random( unsigned long seed ) : _seed( seed ) { randomize(); };
  22.     int integer( int max = INT_MAX )
  23.     {
  24.         randomize();
  25.         return _seed % INT_MAX;
  26.     }
  27.     int integer( int min, int max )
  28.     {
  29.         randomize();
  30.         return min + _seed % (max - min + 1);
  31.     };
  32.     double real( )
  33.     {
  34.         randomize();
  35.         return double( _seed ) / double( ULONG_MAX );
  36.     }
  37. private:
  38.     unsigned long _seed;
  39.     void randomize( )
  40.     {
  41.         _seed = (RANDOM_MULT * _seed + 1) % ULONG_MAX;
  42.  
  43.         ONDEBUG( std::cout << "_seed=" << _seed << std::endl; );
  44.     };
  45. };
  46.  
  47. #if defined( STANDALONE )
  48.  
  49. int main() {
  50.     Random r;
  51.  
  52.     ONDEBUG( std::cout << "RANDOM_MULT=" << RANDOM_MULT << std::endl; );
  53.  
  54.     for( int i = 0; i <= 10; i++ )
  55.     {
  56.         int x = r.integer();
  57.         int y = r.integer( 1, 99 );
  58.         double f = r.real();
  59.         std::cout << "\t" << x << "\t"<< y << "\t" << f << std::endl;
  60.     }
  61.  
  62.     exit( 0 );
  63. }
  64. #endif

Commentaires

Votre commentaire :
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip aide 2000

Entrez un maximum de 2000 caractères.
Améliorez la présentation de votre texte avec les balises de formatage suivantes :
[p]paragraphe[/p], [b]gras[/b], [i]italique[/i], [u]souligné[/u], [s]barré[/s], [quote]citation[/quote], [pre]tel quel[/pre], [br]à la ligne,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]commande[/code], [code=langage]code source en c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].