Sayonara Player
Ranges.h
1/* Ranges.h */
2/*
3 * Copyright (C) 2011-2021 Michael Lugmair
4 *
5 * This file is part of sayonara player
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20#ifndef SAYONARA_PLAYER_RANGES_H
21#define SAYONARA_PLAYER_RANGES_H
22
23#include "Utils/Algorithm.h"
24
25#include <utility>
26#include <vector>
27
28namespace Util
29{
30 using Range = std::pair<int, int>;
31 using RangeList = std::vector<Range>;
32
33 template<typename Element, template<typename> typename Container>
34 Range getNextRange(const Container<Element>& ids, int startIndex)
35 {
36 if(startIndex >= ids.size())
37 {
38 return std::make_pair(-1, -1);
39 }
40
41 auto result = std::make_pair(startIndex, startIndex);
42
43 auto currentIndex = startIndex;
44 auto currentValue = ids[currentIndex];
45 auto expectedValue = currentValue;
46
47 while(currentValue == expectedValue)
48 {
49 result.second = currentIndex;
50
51 currentIndex += 1;
52
53 if(currentIndex == ids.size())
54 {
55 break;
56 }
57
58 expectedValue += 1;
59 currentValue = ids[currentIndex];
60 }
61
62 return result;
63 }
64
65 template<typename Element, template<typename> typename Container>
66 RangeList getRangesFromList(const Container<Element>& ids)
67 {
68 if(ids.empty())
69 {
70 return RangeList{};
71 }
72
73 RangeList result;
74 auto p = getNextRange(ids, 0);
75 while(p.first != -1)
76 {
77 result.push_back(p);
78 p = getNextRange(ids, p.second + 1);
79 }
80
81 return result;
82 }
83
84 template<typename Element, template<typename> typename Container>
85 auto prepareContainerForRangeCalculation(Container<Element> container) -> Container<Element>
86 {
87 std::sort(container.begin(), container.end());
88 Util::Algorithm::remove_duplicates(container);
89
90 return container;
91 }
92}
93
94#endif //SAYONARA_PLAYER_RANGES_H
Helper functions.
Definition: Utils.h:38