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

时间:2015-11-10 19:28:46

标签: c++ algorithm

对于某些测试,我需要使用预定义的唯一性生成一个可能很长的非随机整数序列。我将唯一性定义为浮点数,等于“序列中唯一数字的数量”除以“总序列长度”。该数字应该在(0, 1]半开区间。

我可能需要这些具有不同长度的序列,这是事先未知的 - 所以我需要一个算法来生成这样一个序列,其任何前缀序列具有唯一性,与预定义序列关闭。例如,具有唯一性1,2,...,m,1,2,...,n的序列max(m,n)/(m+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;
  }
}

任何想法如何做到这一点更简单?

1 个答案:

答案 0 :(得分:1)

你没有说任何关于试图让每个数字具有相同基数的事情。下面的代码大致相同,但在某些情况下,它会选择一个数字&#34;反过来&#34; (大多数在序列的早期)。希望简单性和恒定的空间使用能够弥补这一点。

#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());
  }
}