logo CodeStepByStep logo

HitCounter

Language/Type: C# classes algorithms interview

Write a class of objects named HitCounter that keeps track of "hits" or visits to a web site. The idea is that we want to count hits on the site and be able to return the total number of hits in a given time window.

Your class must have the following public members:

member name kind description
HitCounter(window) constructor Constructs a new hit counter for the given window of time. For example, if the window is 10, the hit counter keeps track of hits within the last 10 time increments. The initial time when the counter is constructed is 0. You may assume the window is ≥ 0.
Hit(time) method Records that a user visited the site at the given time. Also updates the notion of the "current time" to the given time. You may assume that the time passed is greater than or equal to the previously current time.
GetHits(time) method Returns the total number of hits that have occured within the given window at the given current time. If the given time is outside the current window range, return 0.

For example:

HitCounter counter = new HitCounter(5);
counter.Hit(1);
counter.Hit(3);
int hits4 = counter.GetHits(4);     // 2

counter.Hit(6);
counter.Hit(6);                     // multiple hits for the same time
counter.Hit(7);
int hits7 = counter.GetHits(7);     // 4  (hit from time 1 is now out of window)
int hits10 = counter.GetHits(10);   // 3  (hit from time 3 is now out of window)
int hits15 = counter.GetHits(15);   // 0  (all hits are now out of window)

Part of the challenge of this problem lies in coming up with an efficient implementation.

You should define the entire class including the class heading, the private fields, and the declarations and definitions of all the public methods and constructor.

Class: Write a complete C# class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.