Untitled
unknown
plain_text
2 years ago
1.8 kB
5
Indexable
/*
Bismillahir Rahmanir Rahim
Author: Abdul_Aziz
*/
#include <chrono>
#include <ctime>
#include <iostream>
#include <deque>
#include <queue>
#include <thread>
using namespace std;
class RateLimitedCalculator {
private:
int callLimit;
queue<chrono::time_point<chrono::system_clock>> callHistory;
public:
RateLimitedCalculator(int callLimit) {
this->callLimit = callLimit;
}
int getSum(int a, int b) {
auto now = chrono::system_clock::now();
// Remove calls older than a minute
while (!callHistory.empty() && chrono::duration_cast<chrono::minutes>(now - callHistory.front()).count() >= 1) {
callHistory.pop();
}
// Check if call limit is reached
if (callHistory.size() >= callLimit) {
throw runtime_error("Rate limit exceeded. Please try again later.");
}
// Add current call to callHistory queue
callHistory.push(now);
return a + b;
}
};
int main() {
// Allow 3 calls per minute
RateLimitedCalculator calculator(3);
try {
cout << calculator.getSum(1, 2) << endl;
cout << calculator.getSum(3, 4) << endl;
cout << calculator.getSum(5, 6) << endl;
// Throws error
cout << calculator.getSum(7, 8) << endl;
// Throws error
cout << calculator.getSum(9, 10) << endl;
}
catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
try{
// Sleep for 1 minute
this_thread::sleep_for(chrono::minutes(1));
cout << calculator.getSum(11, 12) << endl; // Allowed again after reset
}
catch (const exception& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
Editor is loading...
Leave a Comment