-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowerset.c
More file actions
50 lines (44 loc) · 920 Bytes
/
powerset.c
File metadata and controls
50 lines (44 loc) · 920 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
void print_tab(int *tab, int size)
{
for (int i = 0; i < size; i++)
{
if (i == size - 1)
printf("%d", tab[i]);
else
printf("%d ", tab[i]);
}
printf("\n");
}
void powerset(int *tab, int size, int *ope, int ope_size, int res, int index, int sum)
{
if (index == size)
{
if (res == sum)
print_tab(ope, ope_size);
return ;
}
powerset(tab, size, ope, ope_size, res, index + 1, sum);
ope[ope_size] = tab[index];
powerset(tab, size, ope, ope_size + 1, res, index + 1, sum + tab[index]);
}
int main(int ac, char **av)
{
int *tab;
int *ope;
int size = ac - 2;
if (ac < 2)
return (1);
tab = calloc(size, sizeof(int));
ope = calloc(size, sizeof(int));
if (!tab || !ope)
return (1);
for(int i = 0; i < size; i++)
tab[i] = atoi(av[2 + i]);
powerset(tab, size, ope, 0, atoi(av[1]), 0, 0);
free(tab);
free(ope);
return (0);
}