Skip to content

Commit

Permalink
move random int to cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
yxlao committed Jun 24, 2022
1 parent 7af5965 commit bcb0386
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
19 changes: 19 additions & 0 deletions cpp/open3d/utility/Random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@

#include "open3d/utility/Random.h"

#include "open3d/utility/Logging.h"

namespace open3d {
namespace utility {

Expand All @@ -47,5 +49,22 @@ RandomGlobalContext::RandomGlobalContext() {
Seed(rd());
}

RandIntGenerator::RandIntGenerator(const int low, const int high)
: distribution_(low, high) {
if (low < 0) {
utility::LogError("low must be > 0, but got {}.", low);
}
if (low >= high) {
utility::LogError("low must be < high, but got low={} and high={}.",
low, high);
}
}

int RandIntGenerator::operator()() {
std::lock_guard<std::mutex> lock(
*RandomGlobalContext::GetInstance().GetMutex());
return distribution_(*RandomGlobalContext::GetInstance().GetEngine());
}

} // namespace utility
} // namespace open3d
13 changes: 7 additions & 6 deletions cpp/open3d/utility/Random.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,14 @@ class RandomGlobalContext {
/// from a uniform distribution
class RandIntGenerator {
public:
RandIntGenerator(const int min, const int max) : distribution_(min, max) {}
/// Generate uniformly distributed random integer from
/// [low, low + 1, ... high - 1].
///
/// \param low The lower bound (inclusive). \p low must be >= 0.
/// \param high The upper bound (exclusive). \p high must be > \p low.
RandIntGenerator(const int low, const int high);

int operator()() {
std::lock_guard<std::mutex> lock(
*RandomGlobalContext::GetInstance().GetMutex());
return distribution_(*RandomGlobalContext::GetInstance().GetEngine());
}
int operator()();

protected:
std::uniform_int_distribution<int> distribution_;
Expand Down

0 comments on commit bcb0386

Please sign in to comment.