98 lines
1.2 KiB
C
98 lines
1.2 KiB
C
#include "permutations.h"
|
|
|
|
int ft_strlen(char *str)
|
|
{
|
|
int len;
|
|
|
|
len = 0;
|
|
while (str[len])
|
|
len++;
|
|
return (len);
|
|
}
|
|
|
|
void ft_swap(char *a, char *b)
|
|
{
|
|
char temp;
|
|
|
|
temp = *a;
|
|
*a = *b;
|
|
*b = temp;
|
|
}
|
|
|
|
void ft_sort_string(char *str)
|
|
{
|
|
int i;
|
|
int j;
|
|
int len;
|
|
|
|
len = ft_strlen(str);
|
|
i = 0;
|
|
while (i < len - 1)
|
|
{
|
|
j = i + 1;
|
|
while (j < len)
|
|
{
|
|
if (str[i] > str[j])
|
|
ft_swap(&str[i], &str[j]);
|
|
j++;
|
|
}
|
|
i++;
|
|
}
|
|
}
|
|
|
|
void ft_reverse(char *str, int start, int end)
|
|
{
|
|
while (start < end)
|
|
{
|
|
ft_swap(&str[start], &str[end]);
|
|
start++;
|
|
end--;
|
|
}
|
|
}
|
|
|
|
int next_permutation(char *str, int len)
|
|
{
|
|
int i;
|
|
int j;
|
|
|
|
i = len - 2;
|
|
while (i >= 0 && str[i] >= str[i + 1])
|
|
i--;
|
|
if (i < 0)
|
|
return (0);
|
|
j = len - 1;
|
|
while (str[j] <= str[i])
|
|
j--;
|
|
ft_swap(&str[i], &str[j]);
|
|
ft_reverse(str, i + 1, len - 1);
|
|
return (1);
|
|
}
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
char *str;
|
|
char *copy;
|
|
int len;
|
|
int i;
|
|
|
|
if (argc != 2)
|
|
return (1);
|
|
str = argv[1];
|
|
len = ft_strlen(str);
|
|
copy = malloc(sizeof(char) * (len + 1));
|
|
if (!copy)
|
|
return (1);
|
|
i = 0;
|
|
while (i < len)
|
|
{
|
|
copy[i] = str[i];
|
|
i++;
|
|
}
|
|
copy[len] = '\0';
|
|
ft_sort_string(copy);
|
|
puts(copy);
|
|
while (next_permutation(copy, len))
|
|
puts(copy);
|
|
free(copy);
|
|
return (0);
|
|
} |