生成给定字符串的条件排列
Generating conditional permutations of a given string
我有一个非常直接简单的问题。答案可能不是这样。
如果我有一个字符串,说"随机",并说我想生成字符串的排列,条件是我想要一个,‘a’总是在左起第三位,即在arr[2],如果arr保持字符串。有人可能建议生成所有可能的结果,然后寻找arr[2]='0'的结果,但考虑到我的代码是O(n*n!),我认为我真的不想这么做。
我是C++的中级学生。
这取决于条件的指定方式。例如,您可以创建一个从0
到length(YOUR_STRING)
的数字矢量,而不使用与预先固定的字符相对应的索引。
然后,您可以对该向量应用随机混洗,并在混洗向量指示的位置(加上预先固定的字符)写入一个新字符串,其中包含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
版本与生成器一起使用,以便"控制"随机数的生成。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么不;名字在地图上是按顺序排列的吗
- 在没有太多条件句的情况下,我如何避免被零除
- 基于多个条件处理地图中的所有元素
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 条件constexpr函数
- 无论条件是否为true,if总是在c++中执行
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 基于模板值的条件变量
- 按对象的特定方法按升序排列的C++优先级队列
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 将按位if条件转换为普通if条件
- 条件断点在不应该触发时触发
- 为什么简单的算术减法在"if"条件下不起作用?
- 如何在for循环中包含两个索引值的测试条件
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 给定字符的排列算法,具有条件C++的重复
- 生成具有条件的给定字符串的排列
- 生成给定字符串的条件排列