-
Notifications
You must be signed in to change notification settings - Fork 0
/
cost.c
66 lines (59 loc) · 2.19 KB
/
cost.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* cost.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: abertran <abertran@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/02/23 19:01:19 by abertran #+# #+# */
/* Updated: 2023/02/23 22:49:05 by abertran ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/* Calculates the cost of moving each element of stack B into the correct
position in stack A.
cost_b represents the cost of getting the element to the top.
cost_a represents the cost of getting to the right position in stack A. */
void cost(t_stack **stack_a, t_stack **stack_b)
{
t_stack *tmp_a;
t_stack *tmp_b;
int size_a;
int size_b;
tmp_a = *stack_a;
tmp_b = *stack_b;
size_a = get_stack_size(tmp_a);
size_b = get_stack_size(tmp_b);
while (tmp_b)
{
tmp_b->cost_b = tmp_b->pos;
if (tmp_b->pos > size_b / 2)
tmp_b->cost_b = (size_b - tmp_b->pos) * -1;
tmp_b->cost_a = tmp_b->target;
if (tmp_b->target > size_a / 2)
tmp_b->cost_a = (size_a - tmp_b->target) * -1;
tmp_b = tmp_b->next;
}
}
/* Finds the element in stack B with the cheapest cost to move to stack A
and moves it to the correct position in stack A. */
void cheapest_move(t_stack **stack_a, t_stack **stack_b)
{
t_stack *tmp;
int cheapest;
int cost_a;
int cost_b;
tmp = *stack_b;
cheapest = INT_MAX;
while (tmp)
{
if (abs(tmp->cost_a) + abs(tmp->cost_b) < cheapest)
{
cheapest = abs(tmp->cost_a) + abs(tmp->cost_b);
cost_a = tmp->cost_a;
cost_b = tmp->cost_b;
}
tmp = tmp->next;
}
do_move(stack_a, stack_b, cost_a, cost_b);
}