Created
October 21, 2010 18:48
-
-
Save mfoliveira/639055 to your computer and use it in GitHub Desktop.
On-Demand Random Number Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
/* On-Demand Random Number Generator */ | |
#include "Random.h" | |
int main() { | |
/* Randomize seed */ | |
Random::randomize(); | |
/* Number range: 91 <= value < 123 */ | |
Random random(97, 123); | |
/* Numbers */ | |
int number; | |
for (int i = 0; i < 3; ++i) { | |
number = random; | |
cout << number << endl; | |
} | |
/* Characters */ | |
char character; | |
for (int i = 0; i < 3; ++i) { | |
character = random; | |
cout << character << endl; | |
} | |
/* Direct output needs explicit casting */ | |
for (int i = 0; i < 3; ++i) | |
cout << (int) random << endl; | |
/* Done. */ | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* On-Demand Random Number Generator | |
* | |
* (C) Copyright 2010, Mauricio Faria de Oliveira | |
* http://mfoliveira.org | |
* | |
* This program is free software; you can redistribute it and/or modify | |
* it under the terms of the GNU General Public License as published by | |
* the Free Software Foundation; either version 2 of the License, or | |
* (at your option) any later version. | |
*/ | |
#ifndef MFOLIVEIRA_RANDOM_H | |
#define MFOLIVEIRA_RANDOM_H | |
#include <cstdlib> | |
#include <ctime> | |
class Random { | |
protected: | |
/* Base Value: | |
* all random numbers >= base */ | |
int base; | |
/* Limit Value: | |
* all random numbers < limit */ | |
int limit; | |
public: | |
/* Constructor */ | |
Random(int base = 0, int limit = 0) { | |
/* Initialization */ | |
this->base = base; | |
this->limit = limit; | |
} | |
/* Seed Randomizer */ | |
static void randomize() { | |
/* Initialize seed based on current time */ | |
srand(std::time(0)); | |
} | |
/* Cast Operator overload */ | |
template <typename T> | |
operator T() { | |
/* Arbitrarily casting to type T. | |
* This returns 1 <= sizeof(T) <= sizeof(int) random bytes. ;-) */ | |
if (0 == limit) | |
return static_cast<T> | |
(base + std::rand()); | |
else | |
return static_cast<T> | |
(base + std::rand() % (limit - base)); | |
} | |
}; | |
#endif // MFOLIVEIRA_RANDOM_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment