83 lines
1.5 KiB
C++
83 lines
1.5 KiB
C++
#include "Span.hpp"
|
|
|
|
Span::Span(void)
|
|
: _size(0), _max_size(0)
|
|
{
|
|
}
|
|
|
|
Span::Span(const unsigned int &size)
|
|
: _size(0), _max_size(size)
|
|
{
|
|
}
|
|
|
|
Span::Span(const Span &other)
|
|
: _size(other._size), _max_size(other._max_size)
|
|
{
|
|
this->_data = other._data;
|
|
}
|
|
|
|
Span &Span::operator=(const Span &other)
|
|
{
|
|
this->_max_size = other._max_size;
|
|
this->_size = other._size;
|
|
this->_data = other._data;
|
|
|
|
return *this;
|
|
}
|
|
|
|
Span::~Span(void)
|
|
{
|
|
}
|
|
|
|
void Span::addNumber(const int &value)
|
|
{
|
|
if (_size == _max_size)
|
|
throw std::runtime_error("max span size reached");
|
|
_size++;
|
|
_data.push_back(value);
|
|
|
|
}
|
|
|
|
int Span::shortestSpan(void)
|
|
{
|
|
if (_size < 2)
|
|
throw std::runtime_error("not enough values in the span");
|
|
|
|
std::vector<int> sorted = _data;
|
|
size_t shortest = std::numeric_limits<size_t>::max();
|
|
|
|
std::sort(sorted.begin(), sorted.end());
|
|
|
|
for (unsigned int i = 0; i < _size - 1; i++)
|
|
{
|
|
if ((unsigned int)(sorted[i + 1] - sorted[i]) < shortest)
|
|
shortest = sorted[i + 1] - sorted[i];
|
|
}
|
|
return shortest;
|
|
}
|
|
|
|
int Span::longestSpan(void)
|
|
{
|
|
if (_size < 2)
|
|
throw std::runtime_error("not enough values in the span");
|
|
|
|
std::vector<int>::iterator min = std::min_element(_data.begin(), _data.end());
|
|
std::vector<int>::iterator max = std::max_element(_data.begin(), _data.end());
|
|
|
|
return (*max - *min);
|
|
}
|
|
|
|
std::ostream &operator<<(std::ostream &os, const Span &o)
|
|
{
|
|
os << "(size = " << o.getSize() << ") ";
|
|
std::vector<int> const &numbers = o.getData();
|
|
for (unsigned int i = 0; i < numbers.size(); i++)
|
|
{
|
|
os << numbers[i];
|
|
if (i != numbers.size() - 1)
|
|
os << ", ";
|
|
}
|
|
return os;
|
|
}
|
|
|