Asked 3 months ago
0Comments
0 Views
This code implements a message rate limiter. It processes a series of logs, each containing a timestamp and a message. The goal is to determine whether each message should be printed based on the following rules:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <string>
using namespace std;
// Function to check if a message should be printed
bool shouldPrintMessage(int timestamp, string message, unordered_map<string, int>& lastPrintTime) {
// If the message hasn't been seen before
if (lastPrintTime.find(message) == lastPrintTime.end()) {
lastPrintTime[message] = timestamp;
return true;
}
// If the message has been seen before
int oldTimestamp = lastPrintTime[message];
if (timestamp - oldTimestamp >= 10) {
lastPrintTime[message] = timestamp;
return true;
}
return false;
}
int main() {
// Define the logs as a vector of pairs
vector<pair<int, string>> logs = {
{1, "cat"},
{2, "dog"},
{3, "cat"},
{8, "rat"},
{11, "dog"}
};
unordered_map<string, int> lastPrintTime;
for (const auto& log : logs) {
int timestamp = log.first;
string message = log.second;
bool canPrint = shouldPrintMessage(timestamp, message, lastPrintTime);
cout << (canPrint ? "true" : "false") << " ";
}
return 0;
}
vector<pair<int, string>> logs
lastPrintTime
to keep track of when each message was last printedlogs
vectorshouldPrintMessage
functionShare