101 lines
2.7 KiB
C
101 lines
2.7 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: o_ :::::: ::: */
|
|
/* sortmore.c :+: / :+::+: :+: */
|
|
/* +:+ > +:++:+ +:+ */
|
|
/* By: whaffman <whaffman@student.codam.nl> +#+ +:+ +#++#++:++#++ */
|
|
/* +#+ +#+#+ +#++#+ +#+ \o/ */
|
|
/* Created: 2024/11/17 17:25:40 by whaffman #+#+# #+#+# #+# #+# | */
|
|
/* Updated: 2024/11/17 17:39:12 by whaffman ### ### ### ### / \ */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "push_swap.h"
|
|
#include <limits.h>
|
|
|
|
int count_moves_merge_a(int idx_b, t_state *state)
|
|
{
|
|
const int number_b = *(int *) ft_lstat(state->b, idx_b)->content;
|
|
const int idx_a = put_at_index_asc(number_b, state->a);
|
|
const int shortest_a = shortest_rotate(idx_a, ft_lstsize(state->a));
|
|
const int shortest_b = shortest_rotate(idx_b, ft_lstsize(state->b));
|
|
|
|
if (shortest_a * shortest_b > 0)
|
|
return (ft_max(ft_abs(shortest_a), ft_abs(shortest_b)) + 1);
|
|
return (ft_abs(shortest_a) + ft_abs(shortest_b) + 1);
|
|
}
|
|
|
|
int best_merge_a(t_state *state)
|
|
{
|
|
const int size = ft_lstsize(state->b);
|
|
int moves;
|
|
int best_b;
|
|
int min_moves;
|
|
int i;
|
|
|
|
min_moves = INT_MAX;
|
|
best_b = 0;
|
|
i = 0;
|
|
while (i < size)
|
|
{
|
|
moves = count_moves_merge_a(i, state);
|
|
if (moves < min_moves)
|
|
{
|
|
min_moves = moves;
|
|
best_b = i;
|
|
}
|
|
i++;
|
|
}
|
|
return (best_b);
|
|
}
|
|
|
|
void b_merge_a(int idx_b, t_state *state)
|
|
{
|
|
const int number_b = *(int *) ft_lstat(state->b, idx_b)->content;
|
|
const int idx_a = put_at_index_asc(number_b, state->a);
|
|
int shortest_a;
|
|
int shortest_b;
|
|
|
|
shortest_a = shortest_rotate(idx_a, ft_lstsize(state->a));
|
|
shortest_b = shortest_rotate(idx_b, ft_lstsize(state->b));
|
|
common_rotations(&shortest_a, &shortest_b, state);
|
|
rotate_a(shortest_a, state);
|
|
rotate_b(shortest_b, state);
|
|
pa(state);
|
|
}
|
|
|
|
void common_rotations(int *shortest_a, int *shortest_b, t_state *state)
|
|
{
|
|
if (*shortest_a * *shortest_b > 0)
|
|
{
|
|
if (*shortest_a > 0)
|
|
{
|
|
while (*shortest_a > 0 && *shortest_b > 0)
|
|
{
|
|
rr(state);
|
|
(*shortest_a)--;
|
|
(*shortest_b)--;
|
|
}
|
|
}
|
|
else
|
|
{
|
|
while (*shortest_a < 0 && *shortest_b < 0)
|
|
{
|
|
rrr(state);
|
|
(*shortest_a)++;
|
|
(*shortest_b)++;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void sortmore(t_state *state)
|
|
{
|
|
push_all_but_3_b(state);
|
|
if (ft_lstsize(state->a) == 3)
|
|
sort3(state);
|
|
while (state->b)
|
|
b_merge_a(best_merge_a(state), state);
|
|
rotate_a_to_top(state);
|
|
}
|