-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_push_swap.c
127 lines (111 loc) · 2.78 KB
/
utils_push_swap.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils_push_swap.c : : : : : : */
/* : : : */
/* By: margarita <[email protected]> # : # */
/* # # # # # # */
/* Created: 2024/09/20 10:23:15 by margarita # # # # */
/* Updated: 2024/10/02 07:48:17 by margarita ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
/* Checks if the given arguments are all numbers, without duplicates. */
long input_is_correct(char *str)
{
int i;
i = 0;
if ((str[i] == '-' || str[i] == ' ') && (ft_strlen(str) > 1))
i ;
while (str[i] != '\0')
{
if (str[i] < '0' || str[i] > '9')
return (0);
i ;
}
return (1);
}
/* Checks if a stack is sorted.
Returns 0 if the stack is not sorted, 1 if it is sorted. */
int is_sorted(t_stack *stack)
{
while (stack->next != NULL)
{
if (stack->value > stack->next->value)
return (0);
stack = stack->next;
}
return (1);
}
/* Checks if the given arguments are not duplicated. */
int is_duplicated(t_stack *column)
{
t_stack *tmp;
t_stack *tmp2;
tmp = column;
while (tmp)
{
tmp2 = tmp->next;
while (tmp2)
{
if (tmp->value == tmp2->value)
return (1);
tmp2 = tmp2->next;
}
tmp = tmp->next;
}
return (0);
}
/* Fill the stack and check if the input is correct */
void get_numbers(char *argv, t_stack **stack_a)
{
char **param;
long int n;
int i;
param = ft_split(argv);
i = 0;
while (param[i] != NULL)
{
if (input_is_correct(param[i]))
{
n = ft_atoi(param[i]);
if (n > INT_MAX || n < INT_MIN)
error_exit(stack_a, NULL);
stack_add(stack_a, stack_new(n));
}
else
error_exit(NULL, NULL);
free(param[i]);
i ;
}
free(param);
}
/* Assigns an index to each value in stack a.
The indexes are assigned from highest (stack_size) to lowest (1). */
void get_index(t_stack *stack_a, int stack_size)
{
t_stack *ptr;
t_stack *biggest;
int value;
while (--stack_size > 0)
{
ptr = stack_a;
biggest = NULL;
value = INT_MIN;
while (ptr)
{
if (ptr->value == INT_MIN && ptr->index == 0)
ptr->index = 1;
if (ptr->value > value && ptr->index == 0)
{
value = ptr->value;
biggest = ptr;
ptr = ptr->next;
}
else
ptr = ptr->next;
}
if (biggest != NULL)
biggest->index = stack_size;
}
}