From 9c9256631f8d07a1906ba8c09f6e53a250f84a77 Mon Sep 17 00:00:00 2001 From: starnakin Date: Tue, 26 Sep 2023 18:55:42 +0200 Subject: [PATCH] ex01: fix: span understood --- ex01/src/Span.cpp | 13 ++++++++++--- ex01/src/main.cpp | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/ex01/src/Span.cpp b/ex01/src/Span.cpp index 408dda9..4a547c8 100644 --- a/ex01/src/Span.cpp +++ b/ex01/src/Span.cpp @@ -1,4 +1,5 @@ #include "Span.hpp" +#include #include Span::Span() @@ -27,16 +28,22 @@ Span& Span::operator=(const Span& src) int Span::shortestSpan() const { - if (this->_vector.size() == 0) + if (this->_vector.size() < 2) throw std::exception(); - return *std::min_element(this->_vector.begin(), this->_vector.end()); + std::vector 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 { if (this->_vector.size() == 0) 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) diff --git a/ex01/src/main.cpp b/ex01/src/main.cpp index 3386d8e..888fe49 100644 --- a/ex01/src/main.cpp +++ b/ex01/src/main.cpp @@ -53,7 +53,7 @@ int main() span.addNumber(2); span.addNumber(3); span.addNumber(4); - if (span.shortestSpan() == 0) + if (span.shortestSpan() == 1) std::cout << "ok" << std::endl; else std::cout << "failed !" << std::endl;