Write make_limiter(max, window) returning a mutable lambda that, given a timestamp, returns true if the call is allowed (at most max calls in any window starting at the first call of that window).
Solution
main.cpp
#include <iostream>
#include <vector>
auto make_limiter(int max_calls, int window) {
return [max_calls, window, start = -1000000, used = 0](int t) mutable {
if (t - start >= window) { start = t; used = 0; } // new window
if (used < max_calls) { ++used; return true; }
return false;
};
}
int main() {
auto api = make_limiter(3, 10);
std::vector<int> requests{0, 1, 2, 3, 9, 10, 11, 12, 13, 25};
for (int t : requests) std::cout << t << (api(t) ? "+ " : "- ");
std::cout << '\n';
auto login = make_limiter(1, 5);
std::cout << login(0) << login(4) << login(5) << '\n';
return 0;
}
Output Verified by compiling and running
0+ 1+ 2+ 3- 9- 10+ 11+ 12+ 13- 25+
101
The limiter's state (window start and calls used) lives inside the mutable closure, so each limiter is independent – no class needed.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!