Given the variable 'points' which increases every time a variable 'player' collects a point, how do I logically find a way to reward user for finding 30 points inside a 5 minutes limit? There's no countdown timer. e.g player may have 4 points but in 5 minutes if he has 34 points that also counts. I was thinking about using timestamps but I don't really know how to do that.
1 Answers
What you are talking about is a "sliding window". Your window is time based. Record each point's timestamp and slide your window over these timestamps. You will need to pick a time increment to slide your window.
Upon each "slide", count your points. When you get the amount you need, "reward your user". The "upon each slide" means you need some sort of timer that calls a function each time to evaluate the result and do what you want.
For example, set a window for 5 minutes and a slide of 1 second. Don't keep a single variable called points. Instead, simply create an array of timestamps. Every timer tick (of 1 second in this case), count the number of timestamps that match t - 5 minutes to t now; if there are 30 or more, you've met your threshold and can reward your super-fast user. If you need the actual value, that may be 34, well, you've just computed it, so you can use it.
There may be ways to optimize this. I've provided the naive approach. Timestamps that have gone out of range can be deleted to save space.
If there are "points going into the window" that count, then just add them to the sum.

- 20,354
- 4
- 60
- 103
-
In general you could have a cycling array of length **30**, with either a timestamp or a struct with a timestamp and a pointer to the point (if that is at interest to you). Whenever you enter a timestamp, you just enter it at point# modulo **30** (you can set it back to zero if you want) and check whether the timestamp at the slot afterwards (in the cyclical sense) is less than **5 mins** away. This is just the cyclical simplification of a sliding window. – Ninetails Jul 08 '19 at 00:45
-
Yes, I like me some **%**. This is a good way to avoid allocations in this case. – Kit Jul 08 '19 at 14:24