From: Dominik Kaiser Date: Sat, 13 Apr 2024 15:49:06 +0000 (+0200) Subject: Add cmd optimization X-Git-Url: https://git.dkaiser.de/?a=commitdiff_plain;h=5427f29f7f8b4a6691330c2fc8a1c24027d8fe71;p=42%2Fpush_swap.git Add cmd optimization After the sorting algorithm was executed remove unneccessary commands. --- diff --git a/Makefile b/Makefile index 5aeb059..5de184b 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ LIBFT = libft CC = cc CFLAGS = -Wall -Wextra -Werror -SRC_FILES = main.c input_handling.c stack_utils.c command_handling.c sorting.c stack_optimization.c +SRC_FILES = main.c input_handling.c stack_utils.c command_handling.c sorting.c stack_optimization.c cmd_optimization.c OBJ_FILES = $(SRC_FILES:%.c=%.o) LIB_DIR = $(LIBFT) diff --git a/cmd_optimization.c b/cmd_optimization.c new file mode 100644 index 0000000..2d93252 --- /dev/null +++ b/cmd_optimization.c @@ -0,0 +1,85 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* cmd_optimization.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: dkaiser next) */ +/* { */ +/* if ((*(enum e_pscmd *)cur->content == PA */ +/* && *(enum e_pscmd *)cur->next->content == PB) */ +/* || (*(enum e_pscmd *)cur->content == PA */ +/* && *(enum e_pscmd *)cur->next->content == PB)) */ +/* { */ +/* if (last) */ +/* last->next = cur->next->next; */ +/* else */ +/* (*cmds)->next = cur->next->next; */ +/* ft_lstdelone(cur->next, free); */ +/* ft_lstdelone(cur, free); */ +/* optimizations++; */ +/* } */ +/* if (!optimizations) */ +/* { */ +/* last = cur; */ +/* cur = cur->next; */ +/* } */ +/* else */ +/* break; */ +/* } */ +/* if (optimizations) */ +/* optimize_commands(cmds); */ +/* } */ + +static enum e_pscmd get_cmd(t_list *cmd) +{ + if (cmd) + return (*(enum e_pscmd*)cmd->content); + else + return NO_CMD; +} + +void optimize_commands(t_list **cmds) +{ + t_list *cur; + t_list *last; + int optimizations; + + cur = *cmds; + last = cur; + optimizations = 0; + + while (cur->next) + { + if ((get_cmd(cur) == PA && get_cmd(cur->next) == PB) || (get_cmd(cur) == PB && get_cmd(cur->next) == PA)) + { + last->next = cur->next->next; + ft_lstdelone(cur->next, free); + ft_lstdelone(cur, free); + optimizations++; + } + last = last->next; + cur = last->next; + } + if (optimizations) + optimize_commands(cmds); +} diff --git a/main.c b/main.c index fbeee27..a3e1375 100644 --- a/main.c +++ b/main.c @@ -6,7 +6,7 @@ /* By: dkaiser content >> bit) % 2 == 0) + if (*stack_a && (*(int *)(*stack_a)->content >> bit) % 2 == 0) run_command(stack_a, stack_b, cmds, PB); - else + else if ((*stack_a)->next) run_command(stack_a, stack_b, cmds, RA); i++; }