【发布时间】:2017-05-28 16:43:57
【问题描述】:
我正在尝试编写一个程序,该程序根据存储在多个数组中的单词列表生成排列。 例如,我的程序要求 2 组这样的单词:
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;
}
知道groups数组可能有可变的大小,如何正确地做到这一点?
【问题讨论】:
-
这看起来像笛卡尔积,而不是排列
-
@EliKorvigo 这是真的。我猜它们都属于组合学,只是两个不同的应用程序。
-
我写它是因为标题令人困惑。在某些时候,人们会在谷歌上搜索与排列相关的东西,最终可能会发现它根本不相关。同时,寻找产品实施的人将无法找到您的解决方案。从社区的角度来看,这是一个有用的问题。
标签: c arrays algorithm multidimensional-array permutation