【发布时间】:2021-09-15 20:14:03
【问题描述】:
我很难找到它的基本逻辑。我知道递归会有所帮助,但我不知道如何处理它。我的困难在于在基本情况下处理发送/打印数组。我所做的一切都只能迭代最后一个数字,不知道如何处理其他数字。
如果 n 为 2:
$>./a.out | cat -e
01, 02, 03, ..., 09, 12, ..., 79, 89$
如果 n 是 3,事情会变得更难:
012, 013, 014, ..., 123, 124, ..., 134, 135,... 234, ..., 789$
我的代码远没有工作
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
void ft_putchar(char c)
{
write(1, &c, 1);
}
bool is_consecutive(int arr[], int n)
{
int last_value = 9;
if ( n <= 0 )
return false;
while ( --n ) {
if ( arr[n] != last_value-- )
return false;
}
return true;
}
void ft_print_screen(int *t, int size)
{
int i;
i = 0;
while (i < size)
{
ft_putchar(t[i] + '0');
i++;
}
if (is_consecutive(t, size) != true)
{
ft_putchar(',');
ft_putchar(' ');
}
}
void ft_print_combn(int n)
{
int i;
int tab[n];
i = 0;
if (n == 1)
while (i < 10)
{
ft_putchar(i + '0');
i++;
}
while (i < n)
{
tab[i] = 0;
i++;
}
while (tab[0] <= (10 - n) && n > 1)
{
ft_print_screen(tab, n);
tab[n - 1]++;
i = n;
while (i && n > 1)
{
i--;
if (tab[i] > 9)
{
tab[i - 1]++;
tab[i] = 0;
}
}
}
}
void main(int argc, char *argv[])
{
int x = atoi(argv[1]);
ft_print_combn(x);
}
【问题讨论】:
-
首先,澄清问题。您的标题表明目标是创建“所有”组合,但您显示了两个数字组合的部分列表和三个数字组合的单独部分列表。该函数是否需要列出所有组合或仅列出具有固定数量数字的组合?如果它必须列出所有组合,那么升序是什么? 09 是在 012 之前还是之后?
-
第二,一旦你弄明白了,忘掉C代码,想想一个算法来遍历所有的组合。向自己描述该算法。
-
为什么使用
write来生成输出,而不是printf或putchar或<stdio.h>的任何其他缓冲输出函数?您通常不必直接使用read或write。 -
@TomKarzes 因为它将由自动评分系统进行评估
-
你可以在 StackOverflow 上搜索“[c] generate combination”来找到很多解决这个问题的问题。其中应该有一些适合你需要的。
标签: c logic combinations