push_swap/push_swap.c
2022-12-07 20:13:22 +01:00

151 lines
3 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* push_swap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/23 16:48:12 by erey-bet #+# #+# */
/* Updated: 2022/12/07 18:35:18 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/*void ft_putchar(char c)
{
write(1, &c, 1);
}*/
/*void print_stack(t_stack sa, t_stack sb)
{
write(1, "A: ", 3);
for (int i = 0; i < sa.len; i++)
{
ft_putchar(sa.list[i] + '0');
write(1, ", ", 2);
}
ft_putchar('\n');
if (sb.len > 0)
{
write(1, "B: ", 3);
for (int i = 0; i < sb.len; i++)
{
ft_putchar(sb.list[i] + '0');
write(1, ", ", 2);
}
ft_putchar('\n');
}
}*/
/*void print_one_stack(t_stack s)
{
write(1, "A: ", 3);
for (int i = 0; i < s.len; i++)
{
ft_putchar(s.list[i] + '0');
write(1, ", ", 2);
}
ft_putchar('\n');
}*/
void post_push_swap(t_stack sa, t_stack sb, int x, int sa_len)
{
int i;
int y;
y = 0;
while (x-- > 0 && !check_sa(sa))
{
i = 0;
while (i < sa_len && !(check_sa(sa) && sb.len == 0))
{
if (((sa.list[0] >> y) & 1) == 0)
push(&sa, &sb, "b");
else
rotate(&sa, "a");
i++;
}
while (sb.len > 0)
push(&sb, &sa, "a");
y++;
}
}
void pre_push_swap(long *tab, int len)
{
int x;
int sa_len;
t_stack sa;
t_stack sb;
sa.list = get_index(tab, len);
if (sa.list == NULL)
return ;
sa.len = len;
sa_len = len;
sb.list = malloc(sizeof(long) * (len + 1));
if (sb.list == NULL)
return ;
sb.len = 0;
x = max_len_binary(sa);
post_push_swap(sa, sb, x, sa_len);
free(sa.list);
free(sb.list);
}
void push_swap_3(long *tab, int len)
{
t_stack sa;
sa.list = get_index(tab, len);
sa.len = len;
while (!check_sa(sa))
{
if (sa.list[0] > sa.list[1])
{
rotate(&sa, "a");
if (sa.list[0] > sa.list[1])
swap(&sa, "a");
}
else
swap(&sa, "a");
}
}
void push_swap_5(long *tab, int len)
{
t_stack sa;
t_stack sb;
sa.list = get_index(tab, len);
sa.len = len;
sb.list = malloc(sizeof(long) * (len + 1));
if (sb.list == NULL)
return ;
sb.len = 0;
while (sb.len != 2)
{
while (get_min(sa.list, sa.len) != 0)
rotate(&sa, "a");
push(&sa, &sb, "b");
}
push_swap_3(sa.list, sa.len);
while (sb.len > 0)
push(&sb, &sa, "a");
}
int main(int argc, char *argv[])
{
long *tab;
tab = malloc(sizeof(long) * (argc + 1));
if (tab == NULL)
return (1);
if (argc > 1)
if (parsing(argc, argv, tab) == 1)
return (1);
free(tab);
return (0);
}