-
Notifications
You must be signed in to change notification settings - Fork 0
/
push_swap.c
106 lines (96 loc) · 2.6 KB
/
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* push_swap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bsyvasal <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/12/14 14:55:15 by bsyvasal #+# #+# */
/* Updated: 2023/12/14 14:55:15 by bsyvasal ### ########.fr */
/* */
/* ************************************************************************** */
#include "push_swap.h"
static int freeandreturn(int ret, int *stack)
{
free(stack);
write(2, "Error\n", 6);
return (ret);
}
static int *addtostack(char **list, int *i)
{
int *stack;
*i = validate_and_count(list);
if (!*i)
return (NULL);
stack = ft_calloc(sizeof(int), *i);
if (!stack)
return (NULL);
*i = -1;
while (list[++*i])
{
stack[*i] = ft_atoi(list[*i]);
if ((stack[*i] < 0 && list[*i][0] != '-')
|| (stack[*i] > 0 && list[*i][0] == '-'))
{
free(stack);
return (NULL);
}
}
return (stack);
}
static int check_dup(t_stacks *stacks)
{
int i;
int j;
i = -1;
while (++i < stacks->asize - 1)
{
j = i + 1;
while (j < stacks->asize)
{
if (stacks->a[i] == stacks->a[j++])
return (0);
}
}
return (1);
}
static int initialize(int argc, char *argv[], t_stacks *stacks)
{
char **tmp;
if (!*argv[1])
return (write(2, "Error\n", 6));
if (argc == 2)
{
tmp = ft_split(argv[1], ' ');
if (!tmp)
return (0);
stacks->a = addtostack(tmp, &stacks->asize);
free_stringarray(tmp);
}
else
stacks->a = addtostack(argv + 1, &stacks->asize);
if (!stacks->a)
return (write(2, "Error\n", 6));
if (check_dup(stacks) == 0)
return (freeandreturn(0, stacks->a));
stacks->b = ft_calloc(sizeof(int), stacks->asize);
if (!stacks->b)
return (freeandreturn(0, stacks->a));
stacks->bsize = 0;
return (-1);
}
int main(int argc, char *argv[])
{
t_stacks stacks;
if (argc < 2)
return (1);
if (initialize(argc, argv, &stacks) != -1)
return (2);
if (is_ordered(stacks.a, stacks.asize) != -1)
simple_sort(&stacks, 1);
else
turk_sort(&stacks, 1);
free(stacks.a);
free(stacks.b);
return (0);
}