我正试图编写一个程序,用于在存储到多个数组中的单词列表中生成排列。 例如,我的程序要求的2组字是这样的:C多个数组排列算法
words #1: abc def ghi
words #2: 123 456
什么,我想有是这样的输出:
abc 123 | abc 456 | def 123 | def 456 | ghi 123 | ghi 456
或者:
123 abc | 123 def | 123 ghi | 456 abc | 456 def | 456 ghi
的顺序无关紧要。
我可能会使字组的数组具有不固定的大小。然后输入将是:
words #1: abc def ghi
words #2: 123 456
words #3: ** --
和输出:
abc 123 ** | abc 123 -- | abc 456 ** | abc 456 -- | def 123 ** | def 123 -- | def 456 ** | def 456 -- | ghi 123 ** | ghi 123 -- | ghi 456 ** | ghi 456 --
我想我不得不考虑使用递归函数,但我有点困惑。 以下是我已经写了:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct permut_word_s {
char *str;
} permut_word_t;
typedef struct permut_group_s {
permut_word_t *words;
int nb_words;
} permut_group_t;
static int split(char *str,
char *token,
permut_group_t *g) {
permut_word_t *a = NULL;
permut_word_t *t = NULL;
char *p = NULL;
int nbw = 0;
int l = 0;
if(!str || !token || !g) {
return -1;
}
p = strtok(str, token);
while(p != NULL) {
if(!(t = realloc(a, (nbw + 1) * sizeof(permut_word_t)))) {
return -1;
}
if(!(t[nbw].str = malloc(strlen(p) + 1))) {
return -1;
}
memset(t[nbw].str, 0, strlen(p) + 1);
if(!(strncpy(t[nbw].str, p, strlen(p)))) {
return -1;
}
nbw++;
p = strtok(NULL, token);
a = t;
}
g->words = a;
g->nb_words = nbw;
return 0;
}
void word_free(permut_word_t *w) {
if(!w) {
return;
}
if(w->str) {
free(w->str);
}
return;
}
void group_free(permut_group_t *g) {
int i = 0;
if(!g) {
return;
}
for(; i < g->nb_words; i++) {
if(&g->words[i]) {
word_free(&g->words[i]);
}
}
free(g->words);
return;
}
void permut(permut_group_t *g,
int cur,
int len) {
int i = 0;
int j = 0;
if(cur == len) {
return;
}
for(i = cur; i < len; i++) {
for(j = 0; j < g[cur].nb_words; j++) {
printf("%s ", g[cur].words[j].str);
}
permut(g, cur + 1, len);
}
}
int main(int argc, char **argv) {
char buf[1024] = { 0 };
permut_group_t *groups = NULL;
int len = 0;
(void)argc;
(void)argv;
if(!(groups = malloc(2 * sizeof(permut_group_t)))) {
return -1;
}
fprintf(stdout, "words #1: ");
fgets(buf, 1024, stdin);
split(buf, " ", &groups[0]);
len++;
fprintf(stdout, "words #2: ");
fgets(buf, 1024, stdin);
split(buf, " ", &groups[1]);
len++;
permut(&groups[0], 0, len);
group_free(&groups[0]);
group_free(&groups[1]);
free(groups);
return 0;
}
如何能做到这一点正确明知组阵列可以具有可变的大小?
这看起来像一个笛卡尔积,不置换 –
@EliKorvigo这是真的。我想他们都属于combinatorics,只是两个不同的应用程序。 – RoadRunner
我写了它,因为标题混乱。在某些时候,人们会搜索与排列相关的东西,最终可能只会发现它根本不相关。与此同时,寻找产品实施的人们将无法找到您的解决方案。从社区的角度来看,这是一个有用的问题。 –