我无法找出一种随意洗牌的方法,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 …Run Code Online (Sandbox Code Playgroud)