如何生成具有预定义*唯一性*的整数序列
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("%dn", generator.Next());
}
}
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 是否基于数组B整数打印数组A中的整数
- 如何生成具有预定义*唯一性*的整数序列