21#include "utils/utils.h"
37 minix =
get_minix(stack[mode].n, stack[mode].len);
40 i = wrap_ix(minix + 1, stack[mode].len);
41 while ((mode && stack[mode].n[i] > n)
42 || (!mode && stack[mode].n[i] < n))
44 i = wrap_ix(i + 1, stack[mode].len);
45 if ((mode && i == wrap_ix(minix + 1, stack[mode].len))
46 || (!mode && i == minix))
65 if (i < (stack[mode].len / 2 + 1))
68 while (stack[mode].n[0] != i)
89 if (i < (stack.len / 2 + 1))
91 if (o_i < (o_len / 2 + 1))
97 return (i + (o_len - o_i));
99 if (o_i < (o_len / 2 + 1))
100 return (stack.len - i + o_i);
101 if ((stack.len - i) >= (o_len - o_i))
102 return (stack.len - i);
103 return (o_len - o_i);
119 if (!stack[1 - mode].len)
122 while (++i < stack[mode].len)
123 costs[i] =
rot_cost(stack[1 - mode], i, stack[mode].len,
124 pick_i(stack, 1 - mode, stack[mode].n[i]));
127 if (minix > (stack[mode].len / 2))
128 i = minix - stack[mode].len;
133 < (stack[mode].len / 2 + 1)) * 2, mode));
136 > (stack[mode].len / 2)) * 2, mode));
137 i += 1 + (i > 0) * -2;
139 rot_i(stack, 1 - mode,
pick_i(stack, 1 - mode, stack[mode].n[0]));
152 costs = malloc(
sizeof(
int) * stack[0].len);
154 return (
err(
"Error\n", 1));
155 while (stack[0].len > 3 && !
is_sorted(stack, 0))
157 pick(stack, 0, costs);
167 pick(stack, 1, costs);
int err(char *str, int retval)
Print str to stderr and return retval.
int fallback(int a, int b)
Return a if non-zero, otherwise return b.
int get_minix(int *arr, int len)
Get the index of the smallest element.
int is_sorted(t_stack *stack, int mode)
Check if the contents of a stack are in the correct order relative to the smallest element.
void push(t_stack *stack, int mode)
Push the first element from stack 1 or 2 into the other stack, depending on whether mode is set to 0 ...
void r_rot(t_stack *stack, int mode)
Shift all elements in stack 1, 2, or both up, depending on whether mode is set to 0,...
void rot(t_stack *stack, int mode)
Shift all elements in stack 1, 2, or both down, depending on whether mode is set to 0,...
static int rot_cost(t_stack stack, int o_i, int o_len, int i)
Determine move cost of rotating to an index, considering whether it is shorter to rotate or reverse r...
int sort(t_stack *stack)
Output all instructions required to sort stack a.
static int pick_i(t_stack *stack, int mode, int n)
Find appropriate index for n in stack[mode]
static void rot_i(t_stack *stack, int mode, int i)
Rotate to an index with rotate or reverse rotate, depending on which is shorter.
static void pick(t_stack *stack, int mode, int *costs)
Determine which element to push from stack mode to the opposite stack by comparing their movement cos...
void swap(t_stack *stack, int mode)
Swap the first two elements in stacks 1, 2, or both, depending on whether mode is set to 0,...