Skip to content

Instantly share code, notes, and snippets.

@st-kurilin
Created November 7, 2012 10:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st-kurilin/4030723 to your computer and use it in GitHub Desktop.
Save st-kurilin/4030723 to your computer and use it in GitHub Desktop.
Coding challenge: a sliding window map. Quick dummy impl on Java.
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
/**
* @author Stanislav Kurilin
*/
public class SlidingWindowMap {
private final Set<String> keys;
private final int maxCount;
private final long periodMs;
private long periodStart;
private int countOnPeriod;
private Iterator<String> it;
private String currentKey;
public SlidingWindowMap(Set<String> keys, int maxCount, long periodMs) {
this.keys = keys;
this.maxCount = maxCount;
this.periodMs = periodMs;
periodStart = current();
it = keys.iterator();
}
/**
* @return a key that has been used less than `maxCount` times during the
* past `periodMs` milliseconds or null if no such key exists.
*/
public String getNextKey() {
if (timeToStartNewPeriod()) beginNewPeriod();
if (currentKeyIsValid()) return currentKey();
if (thereAreValidKeys()) return newValidKey();
return null;
}
/**
* @return current ms
*/
private long current() {
return new Date().getTime();
}
/**
* @return true if new period should begin false otherwise
*/
private boolean timeToStartNewPeriod() {
return current() - periodStart > periodMs;
}
/**
* reinitialize counters
*/
private void beginNewPeriod() {
periodStart = current();
countOnPeriod = 0;
it = keys.iterator();
}
/**
* @return true if current key steel valid
*/
private boolean currentKeyIsValid() {
return countOnPeriod < maxCount;
}
/**
* @return current key
*/
private String currentKey() {
countOnPeriod++;
return currentKey;
}
/**
* @return true if there are valid keys available
*/
private boolean thereAreValidKeys() {
return it.hasNext();
}
/**
* @return new valid key
* @throws java.util.NoSuchElementException if not available
*/
private String newValidKey() {
currentKey = it.next();
return currentKey;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment