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