ex01: fix: span understood

This commit is contained in:
starnakin 2023-09-26 18:55:42 +02:00
parent 9a6ffd0e48
commit 9c9256631f
2 changed files with 11 additions and 4 deletions

View File

@ -1,4 +1,5 @@
#include "Span.hpp" #include "Span.hpp"
#include <algorithm>
#include <bits/stdc++.h> #include <bits/stdc++.h>
Span::Span() Span::Span()
@ -27,16 +28,22 @@ Span& Span::operator=(const Span& src)
int Span::shortestSpan() const int Span::shortestSpan() const
{ {
if (this->_vector.size() == 0) if (this->_vector.size() < 2)
throw std::exception(); throw std::exception();
return *std::min_element(this->_vector.begin(), this->_vector.end()); std::vector<int> tmp = this->_vector;
std::sort(tmp.begin(), tmp.end());
int min_range = tmp[1] - tmp[0];
for (unsigned int i = 1; i + 1 != tmp.size(); i++)
if (min_range > tmp[i + 1] - tmp[i])
min_range = tmp[i + 1] - tmp[i];
return min_range;
} }
int Span::longestSpan() const int Span::longestSpan() const
{ {
if (this->_vector.size() == 0) if (this->_vector.size() == 0)
throw std::exception(); throw std::exception();
return *std::max_element(this->_vector.begin(), this->_vector.end()); return *std::max_element(this->_vector.begin(), this->_vector.end()) - *std::min_element(this->_vector.begin(), this->_vector.end());
} }
void Span::addNumber(const int nb) void Span::addNumber(const int nb)

View File

@ -53,7 +53,7 @@ int main()
span.addNumber(2); span.addNumber(2);
span.addNumber(3); span.addNumber(3);
span.addNumber(4); span.addNumber(4);
if (span.shortestSpan() == 0) if (span.shortestSpan() == 1)
std::cout << "ok" << std::endl; std::cout << "ok" << std::endl;
else else
std::cout << "failed !" << std::endl; std::cout << "failed !" << std::endl;