​push_swap /
src / strategies / utils.c
162 commits
03-05-2026
89 lines 2.2 kB
 1/* ************************************************************************** */
 2/*                                                                            */
 3/*                                                        :::      ::::::::   */
 4/*   utils.c                                            :+:      :+:    :+:   */
 5/*                                                    +:+ +:+         +:+     */
 6/*   By: ohaponiu <marvin@42.fr>                    +#+  +:+       +#+        */
 7/*                                                +#+#+#+#+#+   +#+           */
 8/*   Created: 2026/05/03 18:35:51 by ohaponiu          #+#    #+#             */
 9/*   Updated: 2026/05/03 22:21:48 by ohaponiu         ###   ########.fr       */
10/*                                                                            */
11/* ************************************************************************** */
12
13#include "operations.h"
14#include "stack.h"
15#include "strategies.h"
16
17/* find_max = 1 -> look for max, find_max = 0 -> look for min */
18int	find_extremum_pos(t_stack *s, int find_max)
19{
20	int	i;
21	int	pos;
22	int	val;
23
24	val = stack_at(s, 0);
25	pos = 0;
26	i = 0;
27	while (++i < stack_size(s))
28	{
29		if ((find_max && stack_at(s, i) > val)
30			|| (!find_max && stack_at(s, i) < val))
31		{
32			val = stack_at(s, i);
33			pos = i;
34		}
35	}
36	return (pos);
37}
38
39/* position of smallest element > val, or min if none */
40int	find_insert_pos(t_stack *a, int val)
41{
42	int	i;
43	int	pos;
44	int	min_above;
45
46	pos = 0;
47	min_above = -1;
48	i = -1;
49	while (++i < stack_size(a))
50	{
51		if (stack_at(a, i) > val
52			&& (min_above < 0 || stack_at(a, i) < min_above))
53		{
54			min_above = stack_at(a, i);
55			pos = i;
56		}
57	}
58	if (min_above >= 0)
59		return (pos);
60	return (find_extremum_pos(a, 0));
61}
62
63/* rotate A shortest direction to bring pos to top */
64void	rotate_a_to_top(t_stack *a, int pos, t_ops *ops)
65{
66	int	n;
67
68	n = stack_size(a);
69	if (pos <= n / 2)
70		while (pos-- > 0)
71			op_ra(a, ops);
72	else
73		while (pos++ < n)
74			op_rra(a, ops);
75}
76
77/* rotate B shortest direction to bring pos to top */
78void	rotate_b_to_top(t_stack *b, int pos, t_ops *ops)
79{
80	int	n;
81
82	n = stack_size(b);
83	if (pos <= n / 2)
84		while (pos-- > 0)
85			op_rb(b, ops);
86	else
87		while (pos++ < n)
88			op_rrb(b, ops);
89}