85 lines
2.3 KiB
C++
85 lines
2.3 KiB
C++
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* Span.cpp :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: aortigos <aortigos@student.42malaga.com> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2026/04/21 10:29:07 by aortigos #+# #+# */
|
|
/* Updated: 2026/04/21 10:29:07 by aortigos ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "Span.hpp"
|
|
|
|
//////////////////
|
|
// Constructors //
|
|
//////////////////
|
|
|
|
Span::Span() : n(0)
|
|
{
|
|
// std::cout << "Span default constructor called" << std::endl;
|
|
}
|
|
|
|
Span::Span(const Span &other)
|
|
{
|
|
*this = other;
|
|
// std::cout << "Span copy constructor called" << std::endl;
|
|
}
|
|
|
|
Span& Span::operator=(const Span &other)
|
|
{
|
|
if (this != &other)
|
|
{
|
|
this->data = other.data;
|
|
this->n = other.n;
|
|
}
|
|
// std::cout << "Span copy assignment operator called" << std::endl;
|
|
return (*this);
|
|
}
|
|
|
|
Span::~Span()
|
|
{
|
|
// std::cout << "Span destructor called" << std::endl;
|
|
}
|
|
|
|
Span::Span(unsigned int n) : n(n) { }
|
|
|
|
void Span::addNumber(int nb)
|
|
{
|
|
if (data.size() >= n)
|
|
{
|
|
throw std::runtime_error("Span is full.");
|
|
}
|
|
this->data.push_back(nb);
|
|
// std::cout << "addNumber: adding " << nb << std::endl;
|
|
}
|
|
|
|
int Span::shortestSpan()
|
|
{
|
|
if (this->data.size() < 2)
|
|
throw std::runtime_error("Span has no elements to analize.");
|
|
|
|
std::vector<int> vec = this->data;
|
|
std::sort(vec.begin(), vec.end());
|
|
int gap = INT_MAX;
|
|
|
|
for (unsigned int i = 0; i < vec.size() - 1; i++)
|
|
{
|
|
if ((vec[i+1] - vec[i]) < gap)
|
|
gap = vec[i+1] - vec[i];
|
|
}
|
|
return (gap);
|
|
}
|
|
|
|
int Span::longestSpan()
|
|
{
|
|
if (this->data.size() < 2)
|
|
throw std::runtime_error("Span has no elements to analize.");
|
|
|
|
std::vector<int> vec = this->data;
|
|
std::sort(vec.begin(), vec.end());
|
|
|
|
return (vec.back() - vec.front());
|
|
}
|