Call Limiter per User
Implement a class CallLimiter that lets each user make at most limit calls in any window ticks in a row. Time is counted in whole ticks, and now never decreases from one call to the next. Write these methods:
CallLimiter(limit, window)sets up the limiter with no calls recorded.try_call(user, now)is a call byuserat timenow. Count the user's earlier allowed calls whose time is greater thannow - window(a call made exactlywindowticks ago no longer counts). If that count is less thanlimit, the call is allowed: it is recorded and the method returnstrue. Otherwise the call is refused and the method returnsfalse. Refused calls are never counted against the limit.count_allowed(user)returns how many calls byuserhave been allowed so far (0for a user who never called).count_refused(user)returns how many calls byuserhave been refused so far (0for a user who never called).
Each user has their own limit: calls by one user never affect another. The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
CallLimiter(2, 5)
try_call("amy", 1) returns true
try_call("amy", 3) returns true
try_call("amy", 4) returns false
try_call("bob", 4) returns true
try_call("amy", 6) returns true
count_allowed("amy") returns 3
count_refused("amy") returns 1
amy may make two calls in any five ticks. At time 4 her calls at 1 and 3 still count, so the call is refused. At time 6 the call at 1 is exactly five ticks old and no longer counts, so it is allowed.
Constraints
1 <= limit <= 4and1 <= window <= 100 <= now <= 200, andnownever decreases from one call to the nextuseris1to8lowercase letters.- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.