生成给定字符串的条件排列

时间:2013-12-04 19:47:08

标签: c++ conditional unique permutation

我有一个非常直接而简单的问题。答案可能不是这样。

如果我有一个字符串说“RANDOM”,并说我想生成字符串的排列给定条件我想要一个,'A'在第三个从左边总是,即在arr [2]如果arr拿着字符串。有人可能会建议产生所有可能的结果,然后寻找具有arr [2] ='0'的那些结果,因为我的代码是O(n * n!)我不认为我真的想这样做。

我是C ++的中间人。

1 个答案:

答案 0 :(得分:1)

这取决于条件的指定方式。例如,您可以创建一个从0length(YOUR_STRING)的数字向量,而不会将索引对应于预先固定的字符。

然后,您可以将random shuffle应用于该向量,并在由混洗向量(加上预先固定的向量)指示的位置写一个字符为YOUR_STRING的新字符串。

一个例子:

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

就是这样。当然,有多种方法可以改进这些代码。我甚至不知道它是否编译。 您可能希望将random_shuffle版本与生成器一起使用,以便“控制”随机数的生成。