Skip to content

Commit

Permalink
Make sure random behavior is deterministic
Browse files Browse the repository at this point in the history
Ensure random generator is seeded with same seed when inserting vertices to ensure deterministic behavior
  • Loading branch information
artem-ogre committed Nov 26, 2021
1 parent 1d12539 commit cbd5cf3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
19 changes: 14 additions & 5 deletions CDT/include/CDT.h
Original file line number Diff line number Diff line change
Expand Up @@ -517,25 +517,33 @@ struct hash<CDT::V2d<T> >
namespace CDT
{

namespace detail
{

#ifdef CDT_CXX11_IS_SUPPORTED

static mt19937 randGenerator(9001);
inline void shuffle_indices(std::vector<VertInd>& indices)
{
static mt19937 g(9001);
std::shuffle(indices.begin(), indices.end(), g);
std::shuffle(indices.begin(), indices.end(), randGenerator);
}

#else

inline size_t randomCDT(const size_t i)
{
static mt19937 g(9001);
return g() % i;
return randGenerator() % i;
}

inline void shuffle_indices(std::vector<VertInd>& indices)
{
std::random_shuffle(indices.begin(), indices.end(), randomCDT);
}

#endif

} // namespace detail

//-----------------------
// Triangulation methods
//-----------------------
Expand All @@ -550,6 +558,7 @@ void Triangulation<T, TNearPointLocator>::insertVertices(
TGetVertexCoordX getX,
TGetVertexCoordY getY)
{
detail::randGenerator.seed(9001); // ensure deterministic behavior
if(vertices.empty())
{
addSuperTriangle(envelopBox<T>(first, last, getX, getY));
Expand All @@ -573,7 +582,7 @@ void Triangulation<T, TNearPointLocator>::insertVertices(
VertInd value = nExistingVerts;
for(Iter it = ii.begin(); it != ii.end(); ++it, ++value)
*it = value;
shuffle_indices(ii);
detail::shuffle_indices(ii);
for(Iter it = ii.begin(); it != ii.end(); ++it)
insertVertex(*it);
break;
Expand Down
3 changes: 1 addition & 2 deletions CDT/include/CDT.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ typedef std::deque<TriInd> TriDeque;

namespace detail
{
static mt19937 randGen(9001);

/// Needed for c++03 compatibility (no uniform initialization available)
template <typename T>
Expand Down Expand Up @@ -659,7 +658,7 @@ TriInd Triangulation<T, TNearPointLocator>::walkTriangles(
const Triangle& t = triangles[currTri];
found = true;
// stochastic offset to randomize which edge we check first
const Index offset(detail::randGen() % 3);
const Index offset(detail::randGenerator() % 3);
for(Index i_(0); i_ < Index(3); ++i_)
{
const Index i((i_ + offset) % 3);
Expand Down

0 comments on commit cbd5cf3

Please sign in to comment.