Want more features on Pastebin? Sign Up, it's FREE!
Guest

SlidingWindowMap code challenge FINAL

By: a guest on Oct 4th, 2012  |  syntax: Java  |  size: 1.21 KB  |  views: 107  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  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.     // Used to store when a key has been used.
  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.         _maxCount = maxCount;
  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.      */
  29.     public String getNextKey() {
  30.         if (_index == _keyUsagesMs.length) {
  31.             _index = 0;
  32.         }
  33.         long now = System.currentTimeMillis();
  34.         if (now >= _keyUsagesMs[_index] + _periodMs) {
  35.             _keyUsagesMs[_index] = now;
  36.             return _keys[_index++ % _keys.length];
  37.         }
  38.         return null;
  39.     }
  40. }
clone this paste RAW Paste Data