How to implement a round-robin circular list and count access requests of an element?
The above answer is correct, just adding one more simpler way of round robin algorithm with list.
import java.util.Iterator;
import java.util.List;
public class MyRoundRobin<T> implements Iterable<T> {
private List<T> coll;
private int index = 0;
public MyRoundRobin(List<T> coll) {
this.coll = coll;
}
public Iterator<T> iterator() {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return true;
}
@Override
public T next() {
if (index >= coll.size()) {
index = 0;
}
T res = coll.get(index++);
return res;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
Comments
-
Wuaner almost 2 years
Scenario:
For a list that have 3 elements:
[A, B, C]
You can circular access it as many times as you want.
And there is an additional counting function records access count of each element.
For example, if accessing it 7 times, should return:
[A, B, C, A, B, C, A]
And have access count of each element as following:
+–––––––––––+–––––––––––––––+ | Element | Access count | +–––––––––––––––––––––––––––+ | A | 3 | +–––––––––––––––––––––––––––+ | B | 2 | +–––––––––––––––––––––––––––+ | C | 2 | +–––––––––––+–––––––––––––––+
Add another additional function that allow caller to specify a elements list that should be filtered. Still use 7 times accessing as a example, filtering
[C]
:[A, B, A, B, A, B, A]
+–––––––––––+–––––––––––––––+ | Element | Access count | +–––––––––––––––––––––––––––+ | A | 4 | +–––––––––––––––––––––––––––+ | B | 3 | +–––––––––––––––––––––––––––+ | C | 0 | +–––––––––––+–––––––––––––––+
And the subsequent calling on
getNextOne()
should always fetch the one that access count is low. Simulate a load-balanced accessing count implementation. So, if second caller attempt to accessing it 10 times, should return:[C, C, C, B, C, A, B, C, A, B, C, A]
+–––––––––––+–––––––––––––––+ | Element | Access count | +–––––––––––––––––––––––––––+ | A | 7 | +–––––––––––––––––––––––––––+ | B | 6 | +–––––––––––––––––––––––––––+ | C | 6 | +–––––––––––+–––––––––––––––+