-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpan.cpp
More file actions
55 lines (42 loc) · 1.23 KB
/
Span.cpp
File metadata and controls
55 lines (42 loc) · 1.23 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
#include "Span.hpp"
Span::Span(unsigned int N) : N(N) {}
Span::Span(const Span &other) : N(other.N), _numbers(other._numbers) {}
Span::~Span() {}
Span &Span::operator=(const Span &other)
{
if (this != &other)
{
N = other.N;
_numbers = other._numbers;
}
return *this;
}
void Span::addNumber(int number)
{
if (_numbers.size() >= N)
throw std::runtime_error("Span is full");
_numbers.push_back(number);
}
unsigned int Span::shortestSpan() const
{
if (_numbers.size() <= 1)
throw std::runtime_error("Not enough numbers to calculate span");
std::vector<int> sorted = _numbers;
std::sort(sorted.begin(), sorted.end());
unsigned int minSpan = UINT_MAX;
for (size_t i = 1; i < sorted.size(); i++)
{
unsigned int span = static_cast<unsigned int>(sorted[i] - sorted[i - 1]);
if (span < minSpan)
minSpan = span;
}
return minSpan;
}
unsigned int Span::longestSpan() const
{
if (_numbers.size() <= 1)
throw std::runtime_error("Not enough numbers to calculate span");
std::vector<int> sorted = _numbers;
std::sort(sorted.begin(), sorted.end());
return static_cast<unsigned int>(sorted.back() - sorted.front());
}