1
0
Files
CPP_Module_08/ex01/Span.cpp
2025-04-16 10:37:35 +02:00

82 lines
2.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Span.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjoly <adjoly@student.42angouleme.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/04/15 09:20:40 by adjoly #+# #+# */
/* Updated: 2025/04/16 10:36:54 by adjoly ### ########.fr */
/* */
/* ************************************************************************** */
#include "Span.hpp"
#include <algorithm>
#include <iterator>
#include <list>
#include <stdexcept>
#include <string>
#include <iostream>
#include <vector>
static void _log(std::string emoji, std::string what, std::string who,
std::string str) {
#ifdef VERBOSE
if (who.empty())
std::cout << "" << emoji << "" << what << ": " << str << std::endl;
else
std::cout << "" << emoji << "" << what << "(" << who << "): " << str
<< std::endl;
#else
(void)emoji, (void)what, (void)who, (void)str;
#endif
}
Span::Span(unsigned int n) : _size(n), _i(0) {
_log("", "Span", "", "n constructor called");
}
Span::Span(void) : _size(1), _i(0) {
_log("", "Span", "", "default constructor called");
}
Span::~Span(void) { _log("", "Span", "", "destructor called"); }
void Span::addNumber(int nb) {
_log("", "Span", "", "addNumber function called");
if (_i >= _size) {
throw std::out_of_range("Span is full");
}
_vec.push_back(nb);
_i++;
}
int Span::shortestSpan(void) {
if (_i < 2) {
throw std::runtime_error("not enough item in Span");
}
std::vector<int> sorted = _vec;
uint32_t shortedSpan = UINT32_MAX;
std::sort(sorted.begin(), sorted.end());
for (std::vector<int>::iterator it = sorted.begin(), next = sorted.begin() + 1;
next != sorted.end(); next++, it++) {
if (static_cast<uint32_t>(*next - *it) < shortedSpan) {
shortedSpan = *next - *it;
}
}
return shortedSpan;
}
int Span::longestSpan(void) {
if (_i < 2) {
throw std::runtime_error("not enough item in Span");
}
std::vector<int>::iterator min = std::min_element(_vec.begin(), _vec.end());
std::vector<int>::iterator max = std::max_element(_vec.begin(), _vec.end());
return (*max - *min);
}