added better permutations

This commit is contained in:
Rui Ribeiro 2025-09-30 17:59:58 +00:00
parent 2b362d0916
commit 96b4d2e9eb

View File

@ -1,94 +1,59 @@
#include <unistd.h> // write #include <stdlib.h>
#include <stdlib.h> // malloc, free #include <stdio.h>
int ft_strlen(const char *s) int length;
char *set;
char *permutation;
int ft_strlen(char *s)
{ {
int len = 0; int i = 0;
while (s[len]) while(s[i])
len++;
return (len);
}
void print_solution(const char *s)
{
write(1, s, ft_strlen(s));
write(1, "\n", 1);
}
void ft_swap(char *a, char *b)
{
char temp = *a;
*a = *b;
*b = temp;
}
void sort_string(char *str, int n)
{
int i;
int j;
i = 0;
while (i < n - 1)
{
j = 0;
while (j < n - i - 1)
{
if (str[j] > str[j + 1])
ft_swap(&str[j], &str[j + 1]);
j++;
}
i++; i++;
} return (i);
} }
void generate_permutations(char *original_str, char *current_perm, int *used, int n, int k) void permutations(int index, char *used)
{ {
if (k == n) if (index == length)
{ {
print_solution(current_perm); printf("%s\n", permutation);
return; return ;
} }
int i = 0; int i = 0;
while (i < n) while (i < length)
{ {
if (used[i] == 0) if (used[i] == '0')
{ {
current_perm[k] = original_str[i]; permutation[index] = set[i];
used[i] = 1; used[i] = '1';
generate_permutations(original_str, current_perm, used, n, k + 1); permutations(index + 1, used);
used[i] = 0; used[i] = '0';
} }
i++; i++;
} }
} }
int main(int argc, char **argv) char *populate_used()
{ {
if (argc != 2 || !argv[1][0]) char *ret = (char *) calloc (length + 1, sizeof(char));
return (0); int i = 0;
while (i < length)
ret[i++] = '0';
return (ret);
}
int n = ft_strlen(argv[1]); int main(int ac, char **av)
char *original_str = argv[1]; {
if (ac != 2)
sort_string(original_str, n);
char *current_perm = (char *)malloc(sizeof(char) * (n + 1));
if (!current_perm)
return (1); return (1);
current_perm[n] = '\0'; set = av[1];
length = ft_strlen(av[1]);
int *used = (int *)calloc(sizeof(int) * n); char *used = populate_used();
if (!used) permutation = (char *) malloc(sizeof(char) * (length + 1));
{ permutations(0, used);
free(current_perm);
return (1);
}
generate_permutations(original_str, current_perm, used, n, 0);
free(current_perm);
free(used); free(used);
free(permutation);
return (0); return (0);
} }