Span.cpp
1 /* ************************************************************************** */ 2 /* */ 3 /* ::: :::::::: */ 4 /* Span.cpp :+: :+: :+: */ 5 /* +:+ +:+ +:+ */ 6 /* By: gychoi <gychoi@student.42seoul.kr> +#+ +:+ +#+ */ 7 /* +#+#+#+#+#+ +#+ */ 8 /* Created: 2023/12/26 00:12:31 by gychoi #+# #+# */ 9 /* Updated: 2023/12/31 01:11:38 by gychoi ### ########.fr */ 10 /* */ 11 /* ************************************************************************** */ 12 13 #include "Span.hpp" 14 15 /* ************************************************************************** */ 16 /* Constructor & Destructor */ 17 /* ************************************************************************** */ 18 19 Span::Span() : mSize(0) 20 { 21 // nothing to do 22 } 23 24 Span::Span(unsigned int n) 25 { 26 if (static_cast<int>(n) < 0) 27 { 28 throw std::out_of_range("Invalid index"); 29 } 30 else 31 { 32 this->mSize = n; 33 this->mVec.reserve(this->mSize); 34 } 35 } 36 37 Span::Span(Span const& target) : mSize(target.mSize) 38 { 39 this->mVec.assign(target.mVec.begin(), target.mVec.end()); 40 } 41 42 Span& Span::operator=(Span const& target) 43 { 44 if (this != &target) 45 { 46 this->mSize = target.mSize; 47 std::vector<int>().swap(this->mVec); 48 this->mVec.assign(target.mVec.begin(), target.mVec.end()); 49 } 50 return *this; 51 } 52 53 Span::~Span() 54 { 55 // nothing to do 56 } 57 58 /* ************************************************************************** */ 59 /* Public Member Function */ 60 /* ************************************************************************** */ 61 62 void Span::addNumber(int number) 63 { 64 if (this->mVec.size() >= this->mSize) 65 { 66 throw std::runtime_error("Can't store number because vector is full"); 67 } 68 else 69 { 70 this->mVec.push_back(number); 71 } 72 } 73 74 unsigned int Span::shortestSpan() const 75 { 76 if (this->mVec.size() <= 1) 77 { 78 throw std::runtime_error("Need to store more numbers to find span"); 79 } 80 else 81 { 82 // enough elements to calculate span 83 } 84 85 std::deque<int> span; 86 int (*abs)(int) = &std::abs; 87 88 std::adjacent_difference(this->mVec.begin(), this->mVec.end(), 89 std::back_inserter(span)); 90 span.pop_front(); 91 std::transform(span.begin(), span.end(), span.begin(), abs); 92 return (*std::min_element(span.begin(), span.end())); 93 } 94 95 unsigned int Span::longestSpan() const 96 { 97 if (this->mVec.size() <= 1) 98 { 99 throw std::runtime_error("Need to store more numbers to find span"); 100 } 101 else 102 { 103 // enough elements to calculate span 104 } 105 106 std::deque<int> span; 107 int (*abs)(int) = &std::abs; 108 109 std::adjacent_difference(this->mVec.begin(), this->mVec.end(), 110 std::back_inserter(span)); 111 span.pop_front(); 112 std::transform(span.begin(), span.end(), span.begin(), abs); 113 return (*std::max_element(span.begin(), span.end())); 114 }