From ad1938b8d83f6aa6b43693ee59ef18904ce5c45b Mon Sep 17 00:00:00 2001 From: Klaus Basan Date: Wed, 23 Sep 2015 15:17:44 +0200 Subject: [PATCH] refs #452, allow to pick random elements from collection (will be used in view resizing) --- src/blackmisc/collection.h | 17 +++++++++++++++++ src/blackmisc/math/mathutils.h | 6 ++++++ src/blackmisc/sequence.h | 18 +++++++++++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/blackmisc/collection.h b/src/blackmisc/collection.h index 067d42c28..f04645ce2 100644 --- a/src/blackmisc/collection.h +++ b/src/blackmisc/collection.h @@ -337,6 +337,23 @@ namespace BlackMisc */ void remove(const CCollection &other) { *this = CCollection(*this).difference(other); } + /*! + * \brief Return some random elements from container + * \param elements how many elements + */ + CCollection randomElements(int elements) const + { + if (this->isEmpty() || elements < 1) { return CCollection(); } + int high = this->size(); + CCollection r; + for (int i = 0; i < elements; i++) + { + int randomIndex = qrand() % high; + r.push_back(*(this->begin()+ randomIndex)); + } + return r; + } + /*! * \brief Test for equality. * \todo Improve inefficient implementation. diff --git a/src/blackmisc/math/mathutils.h b/src/blackmisc/math/mathutils.h index 29b37dc18..f9576efcf 100644 --- a/src/blackmisc/math/mathutils.h +++ b/src/blackmisc/math/mathutils.h @@ -98,6 +98,12 @@ namespace BlackMisc //! Normalize: 0≤ degrees <360 static double normalizeDegrees(double degrees); + + //! Random number between low and high + static int randomIntger(int low, int high) + { + return qrand() % ((high + 1) - low) + low; + } }; } // namespace diff --git a/src/blackmisc/sequence.h b/src/blackmisc/sequence.h index 33ccd2473..50636de99 100644 --- a/src/blackmisc/sequence.h +++ b/src/blackmisc/sequence.h @@ -20,7 +20,6 @@ #include #include #include -#include namespace BlackMisc { @@ -519,6 +518,23 @@ namespace BlackMisc return sorted(BlackMisc::Predicates::MemberLess(key1, keys...)); } + /*! + * \brief Return some random elements from container + * \param elements how many elements + */ + CSequence randomElements(int elements) const + { + if (this->isEmpty() || elements < 1) { return CSequence(); } + int high = this->size(); + CSequence r; + for (int i = 0; i < elements; i++) + { + int randomIndex = qrand() % high; + r.push_back(this->operator [](randomIndex)); + } + return r; + } + //! Equals operator. friend bool operator ==(const CSequence &a, const CSequence &b) {