​push_swap /
src / cli / parse_args.c
162 commits
03-05-2026
100 lines 2.4 kB
  1/* ************************************************************************** */
  2/*                                                                            */
  3/*                                                        :::      ::::::::   */
  4/*   parse_args.c                                       :+:      :+:    :+:   */
  5/*                                                    +:+ +:+         +:+     */
  6/*   By: ohaponiu <marvin@42.fr>                    +#+  +:+       +#+        */
  7/*                                                +#+#+#+#+#+   +#+           */
  8/*   Created: 2026/04/23 17:19:23 by ohaponiu          #+#    #+#             */
  9/*   Updated: 2026/05/03 13:46:44 by mleitao          ###   ########.fr       */
 10/*                                                                            */
 11/* ************************************************************************** */
 12
 13#include "cli.h"
 14#include <libft.h>
 15#include <stdlib.h>
 16
 17static int	count_smaller(int *values, int capacity, int i)
 18{
 19	int	j;
 20	int	count;
 21
 22	count = 0;
 23	j = -1;
 24	while (++j < capacity)
 25		if (values[j] < values[i])
 26			count++;
 27	return (count);
 28}
 29
 30static void	rank_values(int *values, int capacity)
 31{
 32	int	*ranked;
 33	int	i;
 34
 35	ranked = malloc(sizeof(int) * capacity);
 36	if (!ranked)
 37		die(ERR_MALLOC);
 38	i = -1;
 39	while (++i < capacity)
 40		ranked[i] = count_smaller(values, capacity, i);
 41	ft_memcpy(values, ranked, sizeof(int) * capacity);
 42	free(ranked);
 43}
 44
 45static int	*to_values(char **tokens, int capacity)
 46{
 47	int	*values;
 48	int	err;
 49	int	i;
 50	int	j;
 51
 52	if (capacity == 0)
 53		return (NULL);
 54	values = malloc(sizeof(int) * capacity);
 55	if (!values)
 56		return (NULL);
 57	i = -1;
 58	while (++i < capacity)
 59	{
 60		err = ft_atoi_safe(tokens[i], &values[i]);
 61		if (err)
 62			return (free(values), NULL);
 63		j = -1;
 64		while (++j < i)
 65		{
 66			if (values[j] == values[i])
 67				return (free(values), NULL);
 68		}
 69	}
 70	return (values);
 71}
 72
 73int	*parse_args(int argc, char **argv, int *out_capacity)
 74{
 75	char	**tokens;
 76	int		*values;
 77	int		is_split;
 78	int		capacity;
 79
 80	is_split = 0;
 81	tokens = argv;
 82	if (argc == 1)
 83	{
 84		tokens = ft_split(argv[0], ' ');
 85		if (!tokens)
 86			die(ERR_MALLOC);
 87		is_split = 1;
 88	}
 89	capacity = 0;
 90	while (tokens[capacity])
 91		capacity++;
 92	values = to_values(tokens, capacity);
 93	if (is_split)
 94		ft_free_array(tokens);
 95	if (!values)
 96		return (die(ERR_PARSE), NULL);
 97	rank_values(values, capacity);
 98	*out_capacity = capacity;
 99	return (values);
100}