1 Replies - 848 Views - Last Post: 28 September 2011 - 01:26 PM

#1 Anarion   User is offline

  • The Persian Coder
  • member icon

Reputation: 387
  • View blog
  • Posts: 1,663
  • Joined: 16-May 09

Random Number Generator

Posted 26 August 2010 - 11:30 AM

Description: If you get error for time(0), you need to uncomment <ctime> header include. Tested with g++ and it is not needed.a basic class for generating a random integer between two given integers
#include <iostream> //for test program
//---
#include <cstdlib>
//#include <ctime> Uncomment in case of error for time(0)

class ranum {
    ranum() {
        srand(time(0));    //private constructor, only to be used inside ::get()
    }
    ranum(const ranum& rhs); //disable copy constructor
    void operator=(const ranum& rhs); //disable assignment
public:
    static ranum& get(); //get a reference-handle
    int generate(const int& min, const int& max); //return random number in range [min, max]
};

inline ranum& ranum::get() {
    static ranum sngl; //make it a singleton
    return sngl;
}

inline int ranum::generate(const int& min, const int& max) {
    return rand()%(max-min+1) + min;
}

//--- Test Program

using namespace std;

int main() {
    ranum &test = ranum::get(), &test2 = ranum::get(); //get two handles, both are using the same random seed
    cout<<test.generate(-10, 5)<<endl; //print a random integer using range [-10, 5]
    cout<<test2.generate(5, 10)<<endl; //print a random integer using range [5, 10]
    return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Random Number Generator

#2 Gungnir   User is offline

  • Your Imaginary Friend

Reputation: 152
  • View blog
  • Posts: 527
  • Joined: 21-May 11

Re: Random Number Generator

Posted 28 September 2011 - 01:26 PM

srand(time(0)) int generate(int max, int min){return rand()%(max-min+1) + min;} This is 2 lines, not 35.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1