![](/img/trans.png)
[英]How to construct predefined random number generator and seed sequence in constructor?
[英]How to generate a sequence of integers with predefined *uniqueness*?
对于某些测试,我需要生成具有预定义唯一性的可能较长的非随机整数序列。 我将唯一性定义为一个浮点数,等于“序列中唯一数字的数量”除以“序列总长度”。 此数字应在(0, 1]
半开间隔中。
我可能需要这些长度不同的序列,这是事先未知的-因此,我需要一种算法来生成这样的序列,该序列的任何前缀序列都具有唯一性,并且接近于预定义的序列。 例如,具有唯一性max(m,n)/(m+n)
的序列1,2,...,m,1,2,...,n
对我不好。
这个问题看起来很简单,因为该算法应该只生成一个序列-但是我编写的next()
函数(见下文)看起来异常复杂,并且它也大量使用了核心内存:
typedef std::set<uint64_t> USet;
typedef std::map<unsigned, USet> CMap;
const double uniq = 0.25; // --- the predefined uniqueness
uint64_t totalSize = 0; // --- current sequence length
uint64_t uniqSize = 0; // --- current number of unique integers
uint64_t last = 0; // --- last added integer
CMap m; // --- all numbers, grouped by their cardinality
uint64_t next()
{
if (totalSize > 0)
{
const double uniqCurrent = static_cast<double>(uniqSize) / totalSize;
if (uniqCurrent <= uniq)
{
// ------ increase uniqueness by adding a new number to the sequence
const uint64_t k = ++last;
m[1].insert(k);
++totalSize;
++uniqSize;
return k;
}
else
{
// ------ decrease uniqueness by repeating an already used number
CMap::iterator mIt = m.begin();
while (true)
{
assert(mIt != m.cend());
if (mIt->second.size() > 0) break;
++mIt;
}
USet& s = mIt->second;
const USet::iterator sIt = s.cbegin();
const uint64_t k = *sIt;
m[mIt->first + 1].insert(k);
s.erase(sIt);
++totalSize;
return k;
}
}
else
{
m[1].insert(0);
++totalSize;
++uniqSize;
return 0;
}
}
有什么想法可以使事情变得更简单吗?
您没有说要使每个数字都具有相同的基数。 下面的代码大致做到了这一点,但是在某些情况下,它选择了“不合时宜”的数字(通常是在序列的早期)。 希望简单和持续的空间使用能够弥补这一点。
#include <cassert>
#include <cstdio>
class Generator {
public:
explicit Generator(double uniqueness)
: uniqueness_(uniqueness), count_(0), unique_count_(0),
previous_non_unique_(0) {
assert(uniqueness_ > 0.0);
}
int Next() {
++count_;
if (static_cast<double>(unique_count_) / static_cast<double>(count_) <
uniqueness_) {
++unique_count_;
previous_non_unique_ = 1;
return unique_count_;
} else {
--previous_non_unique_;
if (previous_non_unique_ <= 0) {
previous_non_unique_ = unique_count_;
}
return previous_non_unique_;
}
}
private:
const double uniqueness_;
int count_;
int unique_count_;
int previous_non_unique_;
};
int main(void) {
Generator generator(0.25);
while (true) {
std::printf("%d\n", generator.Next());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.