42_push_swap/src/pushswap/move.c

85 lines
2.3 KiB
C

/* ************************************************************************** */
/* */
/* */
/* */
/* */
/* By: ablanken <ablanken at student dot 42barcelona dot com */
/* */
/* Created: foo bar by ablanken */
/* Updated: foo bar by Andrea Blanke */
/* */
/* ************************************************************************** */
#include "push_swap.h"
#include "sort.h"
#include "push_swap_ctx.h"
#include <stdio.h>
static size_t shortest_rot(size_t stack_size, size_t src, size_t dst,
int *direction);
void move_item(t_push_swap_ctx *ctx, t_stack *s, size_t src, size_t dst)
{
t_stackitem_info *item;
size_t rot_count;
int rot_dir;
if ((src == 1 && dst == 0) || (src == 0 && dst == 1))
{
if (s == ctx->stack_a)
push_swap_exec(ctx, ps_op_sa); // TODO: refactor to pass stacks as
// parameters and use stack
// independent ops.
else
push_swap_exec(ctx, ps_op_sb);
return ;
}
stack_info_update(ctx->sinfo, 0);
item = stack_info_getitem_bypos(ctx->sinfo, src);
rot_count = shortest_rot(stack_height(s), src, dst, &rot_dir);
printf("doing %lu %crot\n", rot_count, rot_dir < 0 ? 'r' : 'l');
while (rot_count-- > 0)
{
if (rot_dir < 0)
{
if (ctx->stack_a == s)
push_swap_exec(ctx, ps_op_ra);
else
push_swap_exec(ctx, ps_op_rb);
}
else
{
if (ctx->stack_a == s)
push_swap_exec(ctx, ps_op_rra);
else
push_swap_exec(ctx, ps_op_rrb);
}
}
}
static size_t shortest_rot(size_t size, size_t src, size_t dst,
int *dir)
{
size_t ldist;
size_t rdist;
if (src < dst)
{
ldist = dst - src;
rdist = src + size - dst;
}
else
{
ldist = dst + size - src;
rdist = src - dst;
}
if (ldist < rdist)
{
*dir = 1;
return (ldist);
}
*dir = -1;
return (rdist);
}
// vi: noet sw=4 ts=4: