It depends on how the condition is specified. For instance, you could create a vector of numbers from 0
to length(YOUR_STRING)
, without the indices corresponding to the pre-fixed characters.
Then, you could apply random shuffle to that vector, and write a new string with the characters of YOUR_STRING
in the positions indicated by the shuffled vector (plus the pre-fixed ones).
An example:
std::string yourString = "foo bar bar";
/* pre-fixed characters */
size_t fixedPositionsOrigin[2] = {0, 4}; // "f" and first "b"
size_t fixedPositionsDestin[2] = {8, 2}; // "f" will be put in position 8, first "b" in position 2
/* Other indices */
std::vector<size_t> remainingIndices = {1, 2, 3, 5, 6, 7, 8, 9, 10}; // valid in C++11 only
std::vectro<size_t> shuffledIndices(remainingIndices); // copy
std::random_shuffle(shuffledIndices.begin(), shuffledIndices.end());
/* New string */
std::string newString(yourString.size(), " "); // empty string
// Add pre-fixed characters at correct positions
newString[fixedPositionsDestin[idx]] = yourString[fixedPositionsOrigin[idx]]; // something like this in a loop
// add shuffled characters at correct positions
newString[shuffledIndices[idx]] = yourString[remainingIndices[idx]]; // something like this in a loop
And that's it. Of course, there are multiple ways of improving this code. I don't even know if it compiles.
You may want to use the random_shuffle
version with a generator, so that you "control" the generation of random numbers.