You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

69 lines
2.4 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Span.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/09/19 08:07:10 by narnaud #+# #+# */
/* Updated: 2022/09/19 08:07:11 by narnaud ### ########.fr */
/* */
/* ************************************************************************** */
#include "Span.hpp"
Span::Span(unsigned int N) : _capacity(N) {}
Span::~Span() {}
Span::Span(Span const &sp) { *this = sp; }
Span &Span::operator=(Span const &sp) {
if (this == &sp)
return *this;
_vec = sp._vec;
_capacity = sp._capacity;
return (*this);
}
void Span::addNumber(int const nb) {
if (_vec.size() == _capacity)
throw std::runtime_error("Too much number in span container.");
_vec.push_back(nb);
}
unsigned int Span::shortestSpan() {
std::vector<int>::iterator it;
long ret;
if (_vec.size() < 2)
throw std::runtime_error("Not enought number to get shortest span.");
sort(_vec.begin(), _vec.end());
it = _vec.begin() + 1;
ret = *it - *(it - 1);
for (it = _vec.begin() + 2; it < _vec.end() && ret; it++)
if (*it - *(it - 1) < ret)
ret = *it - *(it - 1);
return (ret);
}
unsigned int Span::longestSpan() {
if (_vec.size() < 2)
throw std::runtime_error("Not enought number to get shortest span.");
sort(_vec.begin(), _vec.end());
return (*(_vec.end() - 1) - *_vec.begin());
}
void Span::addNRandom(unsigned int N) {
if (_vec.size() + N < _capacity)
throw std::runtime_error("Too much number to add into span container.");
srand((unsigned)time(NULL));
for (unsigned int i = 0; i < N; i++)
_vec.push_back((rand() - INT_MAX / 2) * 2);
}
void Span::addRange(std::vector<int>::iterator begin, std::vector<int>::iterator end) {
if (_vec.size() + end - begin > _capacity)
throw std::runtime_error("Container don't have enouth free space for range you want to add.");
std::copy(begin, end, std::back_inserter(_vec));
}