Skip to content

Instantly share code, notes, and snippets.

@gpad
Created June 23, 2014 21:03
Show Gist options
  • Save gpad/11ebf6c676e17e186f02 to your computer and use it in GitHub Desktop.
Save gpad/11ebf6c676e17e186f02 to your computer and use it in GitHub Desktop.
CircularRandom - Usa una lista per decidere quali valori far tornare dal random
#include "StdAfx.h"
#include "GPadAssert.h"
template<typename MyRand>
class MyRandomObject
{
int _sum;
MyRand rand;
public:
MyRandomObject()
:_sum(0)
{
}
void Execute()
{
int times = rand();
for (int i= 0; i < times; ++i)
{
_sum += rand();
}
}
int sum() const
{
return _sum;
}
};
struct RealRandom
{
int operator()()
{
return rand();
}
};
class CircularRandom
{
std::vector<int> _values;
std::vector<int>::iterator _current;
public:
CircularRandom()
:_current(_values.begin())
{
}
CircularRandom& next(int value)
{
_values.push_back(value);
return *this;
}
int operator()()
{
if (_values.empty())
throw std::runtime_error("Could not be empty");
if (_current == _values.end())
_current = _values.end();
return *(_current++);
}
};
template<typename T>
class MockRandom
{
T _rand();
public:
MockRandom(T rand)
:_rand(rand)
{
}
int operator()()
{
return _rand();
}
};
void TestRandom()
{
CircularRandom rand;
rand.next(1).next(666);
//MyRandomObject<RealRandom> obj;
MyRandomObject<MockRandom<CircularRandom>> obj;
obj.Execute();
AssertEquals(obj.sum(), 666);
}
int _tmain(int argc, _TCHAR* argv[])
{
TestRandom();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment