Share ENTIRE SCREEN and Code
Question: Find all delayed flights
Question: Create Cache where 100 entries are allowed in 1 second. Write Function to tell entry is allowed or not?
// Implement a rate limiter - the rate limiter allows 100 requests per second per client
// assume client ID is given to you
// write a class method or a function which returns true if request for client is allowed.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <chrono>
#include <ctime>
#include <thread>
#include <unordered_map>
/*
hashmap <client_id, pair<count, timestamp>>
*/
class test {
std::unordered_map<int, std::pair<int, std::time_t>> um;
public:
bool isAllowed(int clientId){
//long current_timestamp = std::chrono::system_clock::now();
//long current_timestamp = 0;
//std::time_t current_timestamp = std::time(0);
time_t current_timestamp = time(NULL);
std::cout << "current_timestamp=" << current_timestamp << std::endl;
bool out = false;
auto it = um.find(clientId);
if (it == um.end()){
um.insert({clientId, {1, current_timestamp}});
out = true;
}else {
long time = it->second.second;
std::cout << "time=" << time << std::endl;
if (current_timestamp - time > 1){
um.insert({clientId, {1, current_timestamp}});
out = true;
}
else {
auto count = it->second.first;
std::cout << "count=" << count << std::endl;
if (count <= 100) {
um.insert({clientId, {count+1, current_timestamp}});
out = true;
}
}
}
return out;
}
};
int main() {
test obj;
for (int i=0;i<100;++i){
std::cout << obj.isAllowed(1) << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(11));
//std::cout << obj.isAllowed(1) << std::endl;
}
return 0;
}