以随机可重现的顺序生成非重复字节的快速方法
Fast way of generating non-repeating bytes in a random reproducible order
我需要一种快速的方法来生成 256 行,每行有 256 个随机字节并且没有重复。
查找表的生成方式是,第一个表中的元素指向第二个表中指向第一个表中的元素,但这不是重点。
这就是我到目前为止所拥有的(有点慢,尤其是while(random_int>=(int(unused.size(((部分(:
unsigned char lookup_table[256 * 256];
unsigned char lookup_table_inverted[256 * 256];
std::vector<unsigned char> unused;
std::mt19937_64 rng(seed);
std::uniform_int_distribution<int> dist(0, 255);
int random_int;
for (int i = 0; i < 256; ++i)
{
for (int j = 0; j < 256; ++j)
{
unused.push_back((unsigned char)j);
}
for (int j = 0; j < 256; ++j)
{
random_int = dist(rng);
while (random_int >= (int)unused.size())
{
random_int = dist(rng);
}
lookup_table[(i * 256) + j] = unused[random_int];
lookup_table_inverted[(i * 256) + unused[random_int]] = (unsigned char)j;
unused.erase(unused.begin() + random_int);
}
}
已解决:使用std::shuffle()
和std::iota()
。
只需使用标准算法,特别是std::shuffle()
和std::iota
。
不要尝试自己烘焙,它容易出错并且可能效率低下。
unsigned char lookup_table[256 * 256];
unsigned char lookup_table_inverted[256 * 256];
for (int i = 0; i < 256; ++i) {
auto start = lookup_table + 256 * i;
std::iota(start, start + 256, 0);
std::shuffle(start, start + 256, rng);
auto rev = lookup_table_inverted + 256 * i;
for (int c = 0; c < 256; ++c)
rev[start[c]] = c;
}
我会使用std::shuffle
可能是这样的东西:
std::array<unsigned char, 256> get_random_bytes(int seed = 0)
{
thread_local static std::mt19937 mt{std::random_device{}()};
if(seed)
mt.seed(seed);
std::array<unsigned char, 256> bytes;
// fill with the full range of values
std::iota(std::begin(bytes), std::end(bytes), 0);
std::shuffle(std::begin(bytes), std::end(bytes), mt); // randomly shuffle them
return bytes;
}
如果为函数提供非零参数,则用于为 PRNG 设定种子,使结果可重现。
相关文章:
- 找到一种有效的方法,在 2 个巨大的缓冲区上执行 MAX,每字节字节
- 一种从内存中删除 UTF 字节的方法?
- 优雅和最短的方法,只保存一半的字节
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 以随机可重现的顺序生成非重复字节的快速方法
- 使用原始字节向量作为提升序列化的存档的任何方法
- 需要帮助从12个字节生成新的24字节RGB查找阵列,或者是一种更好的编码方法
- 快速简单的方法,以C++为单位一次读取一个字节的 stdin
- C++,在阻塞模式下从套接字读取所有可用字节的最佳方法
- 将数组与传入的字节*缓冲区进行比较的最快方法
- 如何在-120到120之间更改int到char(或其他简单保存为一个字节的简单方法)
- 在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
- 使用C 修改Java方法/字节码
- C 在流中过滤字节的最佳方法
- 将字节数组从c++传递到c#程序集的不同方法是什么
- C :合并并将UINT分为4个字节的最快方法
- 在字节的一部分中存储整数的最快方法
- 在opencv中使用imshow显示字节数组的最快方法是什么?
- x86-64上检查指针范围是否跨越N字节对齐地址的最快方法
- 水平求和SSE无符号字节矢量的最快方法