96 lines
2.3 KiB
C
96 lines
2.3 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* decompose.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: cchauvet <cchauvet@student.42angoulem +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2022/07/31 21:30:41 by cchauvet #+# #+# */
|
|
/* Updated: 2022/07/31 23:38:02 by cchauvet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "rush02.h"
|
|
|
|
char *ft_power_of_ten(unsigned int power)
|
|
{
|
|
char *nbr;
|
|
unsigned int i;
|
|
|
|
nbr = malloc(sizeof(*nbr) * (power + 2));
|
|
nbr[0] = '1';
|
|
i = 1;
|
|
while (i < power)
|
|
{
|
|
nbr[i] = '0';
|
|
i++;
|
|
}
|
|
nbr[i] = '\0';
|
|
return (nbr);
|
|
}
|
|
|
|
void ft_decompose_by_char(char **tab, int *i, int *c, char *nbr)
|
|
{
|
|
tab[*i] = malloc(sizeof(**tab) * 20);
|
|
if (nbr[*c] > '0')
|
|
{
|
|
if ((ft_strlen(nbr) - *c) % 3 == 0)
|
|
{
|
|
tab[(*i)++] = ctoa(nbr[*c], 2);
|
|
tab[*i] = malloc(sizeof(**tab) * 20);
|
|
tab[(*i)++] = "100";
|
|
}
|
|
else if ((ft_strlen(nbr) - *c) % 3 == 2)
|
|
{
|
|
if (nbr[*c] == '1')
|
|
{
|
|
if (nbr[*c + 1] > '0')
|
|
{
|
|
tab[(*i)++] = cat(ctoa(nbr[*c], 3), ctoa(nbr[*c + 1], 2));
|
|
*c = *c + 1;
|
|
}
|
|
}
|
|
else
|
|
tab[(*i)++] = cat(ctoa(nbr[*c], 3), "0");
|
|
}
|
|
else
|
|
tab[(*i)++] = ctoa(nbr[*c], 2);
|
|
}
|
|
}
|
|
|
|
void ft_last_value(char **str, int *i)
|
|
{
|
|
str[*i] = malloc(sizeof(**str));
|
|
str[*i] = "";
|
|
}
|
|
|
|
char **ft_decompose(char *nbr)
|
|
{
|
|
unsigned int packets;
|
|
int *i;
|
|
int *c;
|
|
char **tab;
|
|
|
|
i = malloc(sizeof(*i));
|
|
*i = 0;
|
|
c = malloc(sizeof(*i));
|
|
*c = 0;
|
|
tab = malloc(sizeof(*tab) * 20);
|
|
packets = ft_strlen(nbr) / 3 + ((ft_strlen(nbr) % 3) != 0);
|
|
while (nbr[*c] != '\0')
|
|
{
|
|
ft_decompose_by_char(tab, i, c, nbr);
|
|
if (packets > 1)
|
|
{
|
|
if ((ft_strlen(nbr) - *c) % 3 == 1)
|
|
{
|
|
tab[*i] = malloc(sizeof(**tab) * 20);
|
|
tab[*i] = ft_power_of_ten(ft_strlen(nbr) - *c);
|
|
}
|
|
}
|
|
*c += 1;
|
|
}
|
|
ft_last_value(tab, i);
|
|
return (tab);
|
|
}
|