0

I have a very straight and simple question. The answer may not be so.

If I have a string say "RANDOM", and say I want to generate permutations of the string given the condition that I want an, 'A' at the third from left always,i.e., at arr[2] if arr holds the string. One might suggest generating all possible outcomes and then looking for the ones having arr[2] = '0' BUT given the fact my code is a O(n*n!) I don't think I would really want to do that.

I am an intermediate in C++.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214

1 Answers1

1

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.

dunadar
  • 1,745
  • 12
  • 30