42_push_swap/main.c

110 lines
2.2 KiB
C
Raw Normal View History

2022-11-23 15:44:27 -05:00
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/11/09 17:10:47 by cchauvet #+# #+# */
2022-12-11 09:49:45 -05:00
/* Updated: 2022/12/11 15:48:20 by cchauvet ### ########.fr */
2022-11-23 15:44:27 -05:00
/* */
/* ************************************************************************** */
#include "pushswap.h"
2022-12-11 09:49:45 -05:00
int ft_isin(long int *tab, int len, long int value)
{
int i;
i = 0;
while (i < len)
{
if (tab[i] == value)
return (1);
i++;
}
return (0);
}
void ft_error(char **splitted)
{
int len;
write(2, "Error\n", 6);
len = 0;
while (splitted[len] != NULL)
len++;
ft_cancel(splitted, len);
}
int ft_parse(long int *tab, const char *s)
{
char **splitted;
int i;
splitted = ft_split(s, ' ');
if (splitted == NULL)
return (1);
i = 0;
while (splitted[i] != NULL)
{
if (!ft_isnum(splitted[i]))
{
ft_error(splitted);
return (0);
}
tab[i] = ft_atoi(splitted[i]);
if (ft_isin(tab, i, tab[i]))
{
ft_error(splitted);
return (0);
}
i++;
}
ft_cancel(splitted, i + 1);
return (i);
}
size_t ft_total_len(int argc, char **argv)
{
size_t len;
int i;
len = 0;
i = 1;
while (i < argc)
{
len += ft_seglen(argv[i], ' ');
i++;
}
return (len);
}
2022-11-23 15:44:27 -05:00
int main(int argc, char *argv[])
{
2022-12-06 11:35:45 -05:00
int i;
2022-12-11 09:49:45 -05:00
int y;
size_t len;
2022-12-06 11:35:45 -05:00
long int *tab_a;
2022-11-23 15:44:27 -05:00
2022-12-11 09:49:45 -05:00
tab_a = malloc(ft_total_len(argc, argv) * sizeof(long int));
2022-11-23 15:44:27 -05:00
if (tab_a == NULL)
return (1);
2022-12-11 09:49:45 -05:00
i = 0;
len = 0;
while (++i < argc)
2022-11-23 15:44:27 -05:00
{
2022-12-11 09:49:45 -05:00
y = ft_parse(tab_a + len, argv[i]);
if (y == 0)
2022-11-23 15:44:27 -05:00
{
2022-12-09 09:22:02 -05:00
free(tab_a);
2022-11-23 15:44:27 -05:00
return (1);
}
2022-12-11 09:49:45 -05:00
len += y;
2022-11-23 15:44:27 -05:00
}
2022-12-11 09:49:45 -05:00
if (len >= 2)
ft_sort(tab_a, len);
free(tab_a);
2022-11-23 15:44:27 -05:00
return (0);
}