-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathmerge_intervals.cpp
49 lines (38 loc) · 1.17 KB
/
merge_intervals.cpp
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
// Copyright (c) 2023 Jiri Nytra (jiri.nytra at gmail dot com)
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <flux.hpp>
#include <cstddef>
#include <iostream>
#include <vector>
struct interval_t
{
std::size_t begin;
std::size_t end;
};
std::ostream& operator<<(std::ostream& s, const interval_t& i)
{
return s << '(' << i.begin << ',' << i.end << ')';
}
bool is_overlapped(interval_t a, interval_t b)
{
return a.end >= b.begin;
}
auto merge = [](flux::sequence auto seq) -> interval_t
{
auto begin = flux::front(seq)->begin;
auto end = flux::max(seq, flux::proj(flux::cmp::compare, &interval_t::end))->end;
return {begin, end};
};
int main()
{
std::vector<interval_t> intervals = {{2, 4}, {7, 9}, {11, 13}, {6, 7}, {0, 3}};
// sort intervals according to begin
flux::sort(intervals, flux::proj(flux::cmp::compare, &interval_t::begin));
flux::ref(intervals)
.chunk_by(is_overlapped)
.map(merge)
.write_to(std::cout);
std::cout << std::endl;
// prints [(0,4), (6,9), (11,13)]
}