SHOW:
|
|
- or go back to the newest paste.
1 | import java.util.Set; | |
2 | ||
3 | // Quick experiment of the SlidingWindowMap code challenge | |
4 | // Author: Thierry Kormann - thierry.kormann@me.com | |
5 | // | |
6 | public class SlidingWindowMap { | |
7 | ||
8 | private String[] _keys; | |
9 | private int _maxCount; | |
10 | private long _periodMs; | |
11 | ||
12 | - | private long[] _times; |
12 | + | // Used to store when a key has been used. |
13 | - | private int _count; |
13 | + | private long[] _keyUsagesMs; |
14 | // An index in _keyUsagesMs to know when a key will be available. | |
15 | private int _index; | |
16 | ||
17 | public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) { | |
18 | _keys = new String[keys.size()]; | |
19 | keys.toArray(_keys); | |
20 | - | _times = new long[keys.size() * maxCount]; |
20 | + | |
21 | _periodMs = periodMs; | |
22 | _keyUsagesMs = new long[keys.size() * maxCount]; | |
23 | } | |
24 | ||
25 | /** | |
26 | * @return a key that has been used less than `maxCount` times during the | |
27 | * past `periodMs` milliseconds or null if no such key exists. | |
28 | - | if (_count == _times.length) { |
28 | + | |
29 | - | _count = 0; |
29 | + | |
30 | if (_index == _keyUsagesMs.length) { | |
31 | _index = 0; | |
32 | - | if (now >= _times[_count] + _periodMs) { |
32 | + | |
33 | - | _times[_count] = now; |
33 | + | |
34 | - | return _keys[_count++ % _keys.length]; |
34 | + | if (now >= _keyUsagesMs[_index] + _periodMs) { |
35 | _keyUsagesMs[_index] = now; | |
36 | return _keys[_index++ % _keys.length]; | |
37 | } | |
38 | return null; | |
39 | } | |
40 | } |