125 lines
2.6 KiB
C
125 lines
2.6 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* push_swap.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2022/11/23 16:48:12 by erey-bet #+# #+# */
|
|
/* Updated: 2022/12/11 17:46:16 by erey-bet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "push_swap.h"
|
|
|
|
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");
|
|
}
|
|
free(sa.list);
|
|
}
|
|
|
|
void push_swap_5(long *tab, int len)
|
|
{
|
|
t_stack sa;
|
|
t_stack sb;
|
|
|
|
sa.list = get_index(tab, len);
|
|
sa.len = len;
|
|
if (!init_sb(&sb, len) || !sa.list || check_sa(sa))
|
|
return ;
|
|
while (sb.len != 2)
|
|
{
|
|
while (get_min(sa.list, sa.len) != 0)
|
|
{
|
|
if (get_min(sa.list, sa.len) < 3)
|
|
rotate(&sa, "a");
|
|
else
|
|
rrotate(&sa, "a");
|
|
}
|
|
push(&sa, &sb, "b");
|
|
}
|
|
push_swap_3(sa.list, sa.len);
|
|
while (sb.len > 0)
|
|
push(&sb, &sa, "a");
|
|
free(sa.list);
|
|
free(sb.list);
|
|
}
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
long *tab;
|
|
|
|
tab = malloc(sizeof(long) * (tab_malloc(argc, argv) + 1));
|
|
if (tab == NULL)
|
|
return (1);
|
|
if (argc > 1)
|
|
{
|
|
if (parsing(argc, argv, tab) == 1)
|
|
{
|
|
free(tab);
|
|
return (1);
|
|
}
|
|
}
|
|
free(tab);
|
|
return (0);
|
|
}
|