生成所有未知长度的组合
Generating all combinations with unknown length
我正在练习编程,我用c++生成所有的组合。我知道如何生成所有的组合一定的长度结果是这样的
A A A
A A B
A A C
A B A
A B B
A B C
A C A
A C B
A C C
B A A
.....
我的问题是,我不知道,如何生成未知长度的所有组合。例如,我想要单词长度= 5,程序将生成长度为5的所有组合。怎么做呢?
A A A A A
A A A A B
A A A A C
A A A B A
.........
(对不起我的英文)
查看链接打印所有重复字符的排列
下面的递归函数在页面中,可以创建最后+1个长度的排列。
/* The main function that recursively prints all repeated
permutations of the given string. It uses data[] to store all
permutations one by one */
void allLexicographicRecur (char *str, char* data, int last, int index)
{
int i, len = strlen(str);
// One by one fix all characters at the given index and recur for
// the/ subsequent indexes
for ( i=0; i<len; i++ )
{
// Fix the ith character at index and if this is not the last
// index then recursively call for higher indexes
data[index] = str[i] ;
// If this is the last index then print the string stored in
// data[]
if (index == last)
printf("%sn", data);
else // Recur for higher indexes
allLexicographicRecur (str, data, last, index+1);
}
}
我想这可以达到你的目的。调用allLexicographicRecur,使用'last'参数所需的(长度-1)值
这实际上只是计数。
如果你有字母A, B和C,你是以3为基数计数的。
A为0,B为1,C为2。
又快又脏:
#include <string>
#include <iostream>
int main()
{
for(int i = 0; i < 100; i++) {
const int base = 3;
const char zero_char = 'A';
const size_t length = 5;
std::string out;
for(int n = i; n > 0; ) {
int d = n%base;
out = static_cast<char>(zero_char + d) + out;
n /= base;
}
while(out.length() < length) out = zero_char + out;
std::cout << out << 'n';
}
}
看现场
可能的组合是基数长度,因此如果您希望A, B, C的所有组合都是5位数字,则将第一个for
循环的限制更改为35 (= 243):
for(int i = 0; i < 243; i++)
你可以这样写:
bool increase(const std::string& s, std::vector<std::size_t>& it)
{
for (std::size_t i = 0, size = it.size(); i != size; ++i) {
const std::size_t index = size - 1 - i;
++it[index];
if (it[index] >= s.size()) {
it[index] = 0;
} else {
return true;
}
}
return false;
}
void do_job(const std::string& s,
const std::vector<std::size_t>& it)
{
for (std::size_t i = 0; i != it.size(); ++i) {
std::cout << s[it[i]] << " ";
}
std::cout << std::endl;
}
void cartesian_product(const std::string& s, std::size_t n)
{
std::vector<std::size_t> it(n, 0u);
do {
do_job(s, it);
} while (increase(s, it));
}
演示相关文章:
- 继承期间显示未知行为的子类
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 可组合的lambda/std::函数与std::可选
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 输入中的字符串数未知(以字母表示)
- 混合组合和继承的C++问题
- 具有未知值时的时间复杂性
- 我需要将多个函数组合为一个函数
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 通过组合不同的类型来创建唯一的id
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 链表中写入访问冲突的未知原因
- 正在生成未知类实例
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 模板元编程:如何将参数包组合成新的参数包
- 读取文件时运行时的未知行为
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 检查向量是否具有所有可能的字符组合
- 如何在加密++中将两个源组合成新的源
- 生成所有未知长度的组合