我很难找到一种体面的方法来随机改组中的元素,std::vector
并在一些操作之后恢复原始顺序。我知道这应该是一个相当琐碎的算法,但我想我太累了......
由于我被限制使用自定义随机数生成器类,我想我不能使用std::random_shuffle
,这无济于事,因为我还需要保留原始顺序。所以,我的方法是创建一个std::map
用作原始位置和随机位置之间的映射,如下所示:
std::map<unsigned int, unsigned int> getRandomPermutation (const unsigned int &numberOfElements)
{
std::map<unsigned int, unsigned int> permutation;
//populate the map
for (unsigned int i = 0; i < numberOfElements; i++)
{
permutation[i] = i;
}
//randomize it
for (unsigned int i = 0; i < numberOfElements; i++)
{
//generate a random number in the interval [0, numberOfElements)
unsigned long randomValue = GetRandomInteger(numberOfElements - 1U);
//broken swap implementation
//permutation[i] = randomValue;
//permutation[randomValue] = i;
//use this instead:
std::swap(permutation[i], permutation[randomValue]);
}
return permutation;
}
我不确定上述算法是否是随机排列的正确实现,因此欢迎任何改进。
现在,这就是我如何设法利用这个排列图:
std::vector<BigInteger> doStuff (const std::vector<BigInteger> &input)
{
/// Permute the values in a random order
std::map<unsigned int, unsigned int> permutation = getRandomPermutation(static_cast<unsigned int>(input.size()));
std::vector<BigInteger> temp;
//permute values
for (unsigned int i = 0; i < static_cast<unsigned int>(input.size()); ++i)
{
temp.push_back(input[permutation[i]]);
}
//do all sorts of stuff with temp
/// Reverse the permutation
std::vector<BigInteger> output;
for (unsigned int i = 0; i < static_cast<unsigned int>(input.size()); ++i)
{
output.push_back(temp[permutation[i]]);
}
return output;
}
有些东西告诉我,这个算法我应该只能使用一个std::vector<BigInteger>
,但是,现在,我无法找出最佳解决方案。老实说,我并不真正关心 中的数据input
,所以我什至可以将其设为非常量,覆盖它,然后跳过创建它的副本,但问题是如何实现算法?
如果我做这样的事情,我最终会射中自己的脚,对吧?:)
for (unsigned int i = 0; i < static_cast<unsigned int>(input.size()); ++i)
{
BigInteger aux = input[i];
input[i] = input[permutation[i]];
input[permutation[i]] = aux;
}
编辑:在史蒂夫关于使用“Fisher-Yates”洗牌的评论之后,我getRandomPermutation
相应地改变了我的功能:
std::map<unsigned int, unsigned int> getRandomPermutation (const unsigned int &numberOfElements)
{
std::map<unsigned int, unsigned int> permutation;
//populate the map
for (unsigned int i = 0; i < numberOfElements; i++)
{
permutation[i] = i;
}
//randomize it
for (unsigned int i = numberOfElements - 1; i > 0; --i)
{
//generate a random number in the interval [0, numberOfElements)
unsigned long randomValue = GetRandomInteger(i);
std::swap(permutation[i], permutation[randomValue]);
}
return permutation;
}