如何生成具有预定义*唯一性*的整数序列

How to generate a sequence of integers with predefined *uniqueness*?

本文关键字:整数 唯一性 预定义 何生成      更新时间:2023-10-16

对于某些测试,我需要生成一个潜在的长非随机整数序列,该序列具有预定义的唯一性。我将唯一性定义为一个浮点数,等于"序列中唯一数字的数量"除以"总序列长度"。该数字应在(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());
  }
}