From 8186a78cd634a863999cb30c438b98876d24881c Mon Sep 17 00:00:00 2001 From: Vladimir Byko-Ianko Date: Fri, 3 Mar 2017 19:57:03 +0300 Subject: Moving RandomSample to base. --- base/base.pro | 2 ++ base/random.cpp | 22 ++++++++++++++++++++++ base/random.hpp | 9 +++++++++ 3 files changed, 33 insertions(+) create mode 100644 base/random.cpp create mode 100644 base/random.hpp (limited to 'base') diff --git a/base/base.pro b/base/base.pro index 7eda31055f..71073004a6 100644 --- a/base/base.pro +++ b/base/base.pro @@ -18,6 +18,7 @@ SOURCES += \ logging.cpp \ lower_case.cpp \ normalize_unicode.cpp \ + random.cpp \ shared_buffer_manager.cpp \ src_point.cpp \ string_format.cpp \ @@ -59,6 +60,7 @@ HEADERS += \ mutex.hpp \ newtype.hpp \ observer_list.hpp \ + random.hpp \ range_iterator.hpp \ ref_counted.hpp \ regexp.hpp \ diff --git a/base/random.cpp b/base/random.cpp new file mode 100644 index 0000000000..a6decf8498 --- /dev/null +++ b/base/random.cpp @@ -0,0 +1,22 @@ +#include "base/random.hpp" + +#include +#include + +namespace my +{ +std::vector RandomSample(size_t n, size_t k, std::minstd_rand & rng) +{ + std::vector result(std::min(k, n)); + std::iota(result.begin(), result.end(), 0); + + for (size_t i = k; i < n; ++i) + { + size_t const j = rng() % (i + 1); + if (j < k) + result[j] = i; + } + + return result; +} +} // my diff --git a/base/random.hpp b/base/random.hpp new file mode 100644 index 0000000000..b17189e36c --- /dev/null +++ b/base/random.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +namespace my +{ +std::vector RandomSample(size_t n, size_t k, std::minstd_rand & rng); +} // my -- cgit v1.2.3