I am having trouble finding a decent way to randomly shuffle items in std::vectorand after some operations to restore the original order. I know this should be a pretty trivial algorithm, but I think I'm too tired ...
Since I have a limited user class of random number generators, I think I can’t use std::random_shufflethat in no way helps, because I also need to keep the original order. So, my approach was to create std::map, which serves as a comparison between the original and random positions, for example:
std::map<unsigned int, unsigned int> getRandomPermutation (const unsigned int &numberOfElements)
{
std::map<unsigned int, unsigned int> permutation;
for (unsigned int i = 0; i < numberOfElements; i++)
{
permutation[i] = i;
}
for (unsigned int i = 0; i < numberOfElements; i++)
{
unsigned long randomValue = GetRandomInteger(numberOfElements - 1U);
std::swap(permutation[i], permutation[randomValue]);
}
return permutation;
}
I'm not sure if the above algorithm is the correct implementation for random permutation, so any improvements are welcome.
:
std::vector<BigInteger> doStuff (const std::vector<BigInteger> &input)
{
std::map<unsigned int, unsigned int> permutation = getRandomPermutation(static_cast<unsigned int>(input.size()));
std::vector<BigInteger> temp;
for (unsigned int i = 0; i < static_cast<unsigned int>(input.size()); ++i)
{
temp.push_back(input[permutation[i]]);
}
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;
}
EDIT: , "Fisher-Yates" shuffle, getRandomPermutation :
std::map<unsigned int, unsigned int> getRandomPermutation (const unsigned int &numberOfElements)
{
std::map<unsigned int, unsigned int> permutation;
for (unsigned int i = 0; i < numberOfElements; i++)
{
permutation[i] = i;
}
for (unsigned int i = numberOfElements - 1; i > 0; --i)
{
unsigned long randomValue = GetRandomInteger(i);
std::swap(permutation[i], permutation[randomValue]);
}
return permutation;
}