Skip to content

Commit

Permalink
patch: merge points over inserting them
Browse files Browse the repository at this point in the history
When points can merge together eg [1,5] [6,9] -> [1,9] we transform the value at the insertion point.
  • Loading branch information
Andersama committed Apr 13, 2021
1 parent 20294f0 commit 98c02b0
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions include/ctre/first.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -434,15 +434,58 @@ template <size_t Capacity> class point_set {
obj = tmp;
//std::swap(*it, obj);

used++;
return out;
}
}
constexpr bool can_merge(point lhs, point rhs) noexcept {
point expanded_lhs = lhs;
//expand ranges by 1 in each direction
expanded_lhs.low -= (expanded_lhs.low > INT64_MIN) ? 1 : 0;
expanded_lhs.high += (expanded_lhs.high < INT64_MAX) ? 1 : 0;

point expanded_rhs = rhs;
expanded_rhs.low -= (expanded_rhs.low > INT64_MIN) ? 1 : 0;
expanded_rhs.high += (expanded_rhs.high < INT64_MAX) ? 1 : 0;
//for example [1,5] and [6,9] can merge into [1,9]
return (expanded_lhs.low <= rhs.high && rhs.low <= expanded_lhs.high) ||
(expanded_rhs.low <= lhs.high && lhs.low <= expanded_rhs.high);
}
constexpr point* insert_and_merge_point(int64_t position, int64_t other) {
point obj{ position, other };
auto it = lower_bound(obj);
if (it == end()) {
*it = obj;
used++;
return it;
} else {
auto out = it;
//good chance we can merge here
if (can_merge(*it, obj)) {
//merge the points together vs inserting
it->low = it->low < obj.low ? it->low : obj.low;
it->high = it->high > obj.high ? it->high : obj.high;
return out;
}
auto e = end();
while (it != e) {
auto tmp = *it;
*it = obj;
obj = tmp;
it++;
}
auto tmp = *it;
*it = obj;
obj = tmp;

used++;
return out;
}
}
public:
constexpr point_set() { }
constexpr void insert(int64_t low, int64_t high) {
insert_point(low, high);
//insert_point(high, low);
insert_and_merge_point(low, high);
}
constexpr bool check(int64_t low, int64_t high) {
for (auto r: *this) {
Expand Down

0 comments on commit 98c02b0

Please sign in to comment.