Skip to content

Instantly share code, notes, and snippets.

@CeytiX
Last active September 6, 2015 16:53
Show Gist options
  • Select an option

  • Save CeytiX/b6455f03291004eec7da to your computer and use it in GitHub Desktop.

Select an option

Save CeytiX/b6455f03291004eec7da to your computer and use it in GitHub Desktop.
Return a random integer between MIN and MAX
#include <iostream>
#include "Randint.h"
int main()
{
Randint randint;
std::cout << randint(1, 10) << std::endl; /** displays a number between 1 and 10 **/
randint.setMinMax(5, 12);
std::cout << randint() << std::endl; /** displays a number between 5 and 12 **/
Randint randinteger(-4, 19);
std::cout << randinteger() << std::endl; /** displays a number between -4 and 19 **/
randinteger.setMinMax(randinteger.getMin()+1, randinteger.getMax()+1);
std::cout << randinteger() << std::endl; /** displays a number between -3 and 20 **/
randinteger.setMinMax(20, 10);
std::cout << randinteger() << std::endl; /** displays a number between 10 and 20 **/
std::cout << Randint(12, 35) << std::endl; /** displays a number between 12 and 35 **/
return 0;
}
#endif
#include "Randint.h"
Randint::Randint()
{
srand(time(0));
m_MIN = 1;
m_MAX = 10;
}
Randint::Randint(int min, int max)
{
srand(time(0));
if(max > min)
{
m_MIN = min;
m_MAX = max;
}
else
{
m_MIN = max;
m_MAX = min;
}
}
Randint::~Randint()
{
/** void **/
}
void Randint::setMinMax(int min, int max)
{
if(max > min)
{
m_MIN = min;
m_MAX = max;
}
else
{
m_MIN = max;
m_MAX = min;
}
}
int Randint::getMin()
{
return m_MIN;
}
int Randint::getMax()
{
return m_MAX;
}
int Randint::operator()()
{
return rand()%(m_MAX-m_MIN+1) + m_MIN;
}
int Randint::operator()(int min, int max)
{
if(max > min)
{
return rand()%(max-min+1) + min;
}
else
{
return rand()%(min-max+1) + max;
}
}
#ifndef RANDINT_H_INCLUDED
#define RANDINT_H_INCLUDED
#include <cstdlib>
#include <ctime>
class Randint
{
public:
Randint();
Randint(int, int);
~Randint();
void setMinMax(int, int);
int getMin();
int getMax();
int operator()();
int operator()(int, int);
private:
int m_MIN;
int m_MAX;
};
@CeytiX
Copy link
Author

CeytiX commented Jun 27, 2015

It could be very useful so don't forget to use it !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment