Advertisement
SalmaYasser

Design a Logger Rate Limiter

Jan 16th, 2020
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. class Logger{
  2. public :
  3. unordered_map <string, bool> msgs;
  4. queue< pair <int , string> > sliding_win;
  5. Logger (){
  6.  
  7. }
  8. bool shouldPrintMessage ( int timestamp, string msg )
  9. {
  10. while (!sliding_win.empty())
  11. {
  12. //cout << timestamp << endl;
  13. auto it = sliding_win.front();
  14. string msg_txt = it.second;
  15. int msg_timestamp = it.first;
  16.  
  17. if (timestamp - msg_timestamp >= 10 )
  18. {
  19. sliding_win.pop();
  20. msgs.erase (msg_txt);
  21. }
  22. else
  23. break;
  24.  
  25. }
  26.  
  27. if (msgs.find(msg) != msgs.end())
  28. {
  29. return false;
  30. }
  31.  
  32. msgs[msg] = timestamp;
  33. sliding_win.push({timestamp,msg});
  34. return true;
  35.  
  36. }
  37.  
  38.  
  39. };
  40.  
  41. int main() {
  42. Logger logger = Logger();
  43. // logging string "foo" at timestamp 1
  44. cout <<logger.shouldPrintMessage(1, "foo") << endl; //returns true;
  45.  
  46. // logging string "bar" at timestamp 2
  47. cout << logger.shouldPrintMessage(2,"bar") << endl; //returns true;
  48.  
  49. // logging string "foo" at timestamp 3
  50. cout << logger.shouldPrintMessage(3,"foo") << endl; //returns false;
  51.  
  52. // logging string "bar" at timestamp 8
  53. cout << logger.shouldPrintMessage(8,"bar") << endl; //returns false;
  54.  
  55. // logging string "foo" at timestamp 10
  56. cout << logger.shouldPrintMessage(10,"foo") << endl; //returns false;
  57.  
  58. // logging string "foo" at timestamp 11
  59. cout << logger.shouldPrintMessage(11,"foo") << endl; //returns true;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement