-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpan.cpp
More file actions
69 lines (52 loc) · 1.37 KB
/
Copy pathSpan.cpp
File metadata and controls
69 lines (52 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "Span.hpp"
#include <algorithm>
#include <climits>
Span::Span(unsigned int n) : _capacity(n), _data() {}
Span::Span(const Span &other) : _capacity(other._capacity), _data(other._data) {}
Span &Span::operator=(const Span &other)
{
if (this != &other)
{
_capacity = other._capacity;
_data = other._data;
}
return *this;
}
Span::~Span() {}
void Span::addNumber(int value)
{
if (_data.size() >= _capacity)
throw SpanFullException();
_data.push_back(value);
}
unsigned int Span::shortestSpan() const
{
if (_data.size() < 2)
throw NoSpanException();
std::vector<int> tmp(_data);
std::sort(tmp.begin(), tmp.end());
unsigned int minSpan = UINT_MAX;
for (std::vector<int>::size_type i = 1; i < tmp.size(); ++i)
{
unsigned int diff = static_cast<unsigned int>(tmp[i] - tmp[i - 1]);
if (diff < minSpan)
minSpan = diff;
}
return minSpan;
}
unsigned int Span::longestSpan() const
{
if (_data.size() < 2)
throw NoSpanException();
std::vector<int>::const_iterator minIt = std::min_element(_data.begin(), _data.end());
std::vector<int>::const_iterator maxIt = std::max_element(_data.begin(), _data.end());
return static_cast<unsigned int>(*maxIt - *minIt);
}
const char* Span::SpanFullException::what() const throw()
{
return "Span is full";
}
const char* Span::NoSpanException::what() const throw()
{
return "Not enough elements to calculate span";
}