Last active
December 15, 2022 11:28
-
-
Save kuznetsov-m/804d71910146107b07b90d4ddbe3e33c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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