Files
42_INT_06_pushwap/srcs/push_swap.c
2021-09-27 14:07:52 +02:00

155 lines
2.6 KiB
C

#include "push_swap.h"
int is_ordered(t_stack *list)
{
int cmp;
while (list && list->next)
{
cmp = list->n;
list = list->next;
if (list->n < cmp)
return (0);
}
return (1);
}
int has_doubles(t_stack *list)
{
t_stack *head;
int nbr;
while (list)
{
head = list;
nbr = head->n;
while(head && head->next)
{
head = head->next;
if (head->n == nbr)
return (1);
}
list = list->next;
}
return (0);
}
int check_valid(t_stack *list)
{
if (!list)
return (0);
if (is_ordered(list) == 1)
return (0);
if (has_doubles(list) == 1)
ps_stop(NULL, (t_list *)list, 3);
return (1);
}
int check_flag(int *ac, char ***av)
{
if (ft_strcmp((*av)[1], "-p") == 0)
{
(*av)++;
(*ac)--;
return (1);
}
if (ft_strcmp((*av)[1], "-P") == 0)
{
(*av)++;
(*ac)--;
return (2);
}
return (0);
}
t_stack *fill_stack(t_stack *list, char *nb, char **tab)
{
t_stack *new;
long nbl;
new = ft_calloc(1, sizeof(t_stack));
if (!new)
ps_stop(tab, (t_list *)list, 3);
new->next = list;
list = new;
if (ft_isnumber(nb) == 0)
ps_stop(tab, (t_list *)list, 3);
nbl = ft_atol(nb);
if (nbl < INT_MIN || nbl > INT_MAX)
ps_stop(tab, (t_list *)list, 3);
list->n = nbl;
list->limit = 0;
return (list);
}
t_stack *init_stack(int ac, char **av)
{
char **split;
t_stack *list;
int i;
list = NULL;
if (ac > 2)
while (--ac)
list = fill_stack(list, av[ac], av);
else if (ac == 2)
{
split = ft_split(av[1], ' ');
i = 0;
while (split[i] != NULL)
i++;
while (--i >= 0)
list = fill_stack(list, split[i], split);
ft_free_tab(split);
}
return (list);
}
/*
** the chained list "solution" is created with specials first two elements :
** they are pointers to stack a and b, so it can be accessed by fill_solution()
*/
t_list *launch_algo(t_stack **a, t_stack **b, int flag)
{
t_list *solution;
solution = ft_lstnew(a);
ft_lstadd_back(&solution, ft_lstnew(b));
if (flag)
{
fill_solution(solution, "start");
mark_step(solution, "start");
}
if (sublist_size(*a) <= 3)
special_sort_3(a, solution);
else if (sublist_size(*a) <= 5)
special_sort_5(a, b, solution);
else
hugo_sort(a, b, solution);
// bubble_sort_luke(a, b, solution);
return (solution);
}
int main(int ac, char **av)
{
t_stack *a;
t_stack *b;
t_list *solution;
int flag;
if (ac < 2)
ps_stop(NULL, NULL, 1);
flag = check_flag(&ac, &av);
a = init_stack(ac, av);
b = NULL;
if (check_valid(a) == 1)
{
solution = launch_algo(&a, &b, flag);
print_result(solution, flag);
ps_stop(NULL, solution, 0);
}
else
ps_stop(NULL, (t_list *)a, -1);
return (0);
}