Advertisement
MrModest

Yandex - RobotStatistics.cs

Jun 5th, 2021 (edited)
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | None | 0 0
  1. // Есть последовательность событий, каждое событие это пара user_id, time, события отсортированы по времени.
  2. // Нужно уметь отвечать на вопрос, сколько за последние 5 минут было пользователей, которые задали >= 1000 запросов.
  3. //
  4. // class RobotStatistics {
  5. //   void OnEvent(time_t now, int userId);
  6. //   int GetRobotCount(time_t now);
  7. // };
  8.  
  9. // новое решение: https://pastebin.com/BxRjsSVf
  10. class RobotStatistics
  11. {
  12.     private List<(DateTime time, int userId)> _requests = new List<(DateTime time, int userId)>();
  13.     private Dictionary<int, int> _countByUser = new Dictionary<int, int>();
  14.     private int _robotCount;
  15.    
  16.     public void OnEvent(DateTime time, int userId)
  17.     {
  18.         _requests.Add((time, userId));
  19.        
  20.         if (!countByUser.Contains(userId))
  21.         {
  22.             countByUser[userId] = 0;
  23.         }
  24.         countByUser[userId]++;
  25.        
  26.         if (_countByUser[_requests[i].userId] == 1000)
  27.         {
  28.             _robotCount++;
  29.         }
  30.        
  31.         ClearOldRequests(DateTime time);
  32.     }
  33.    
  34.     private void ClearOldRequests(DateTime time)
  35.     {
  36.         var startTime = time.AddMinute(-5);
  37.         for(var i = 0; i < _requests.Length && _requests[i].time < startTime; i++)
  38.         {
  39.             if (_countByUser[_requests[i].userId] == 1000)
  40.             {
  41.                 _robotCount--;
  42.             }
  43.             _countByUser[_requests[i].userId]--;
  44.         }
  45.         // тут ещё надо удалить как-то неактуальные запросы, возможно переделать List<> в LinkedList<>
  46.     }
  47.    
  48.     public int GetRobotCount(DateTime time)
  49.     {
  50.         ClearOldRequests(time);
  51.        
  52.         return _robotCount;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement