Skip to content

Instantly share code, notes, and snippets.

@kuznetsov-m
Last active December 15, 2022 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuznetsov-m/804d71910146107b07b90d4ddbe3e33c to your computer and use it in GitHub Desktop.
Save kuznetsov-m/804d71910146107b07b90d4ddbe3e33c to your computer and use it in GitHub Desktop.
// sum_series(
// a={{0, 2}, {5, 1}},
// b={{2, 4}, {3, 6}, {8, 7}}
// ) -> {{0, 2}, {2, 6}, {3, 8}, {5, 7}, {8, 8}}
#include <vector>
struct Point {
int time;
int value;
};
std::vector<Point> sum_series(const std::vector<Point>& a, const std::vector<Point>& b) {
std::vector<Point> r;
r.reserve(a.size() + b.size());
size_t i = 0;
size_t j = 0;
while (i < a.size() && j < b.size()) {
if (a[i].time < b[j].time) {
// можно упаковать push_back() в лямбду
r.push_back({
a[i].time,
a[i].value + (j != 0 ? b[j-1].value : 0)
});
++i;
} else {
r.push_back({
b[j].time,
b[j].value + (i != 0 ? a[i-1].value : 0)
});
++j;
}
}
while (i < a.size()) {
r.push_back({
a[i].time,
a[i].value + (j != 0 ? b[j-1].value : 0)
});
++i;
}
while (j < b.size()) {
r.push_back({
b[j].time,
b[j].value + (i != 0 ? a[i-1].value : 0)
});
++j;
}
return r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment