Skip to content
Advertisement

How to implement a round-robin circular list and count access requests of an element?

Scenario:

For a list that have 3 elements:

JavaScript

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:

JavaScript

And have access count of each element as following:

JavaScript

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]:

JavaScript
JavaScript

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:

JavaScript
JavaScript

Advertisement

Answer

Guava provides an Iterables.cycle(), coupled with a Multiset for counting and you’re done:

JavaScript

Output:

JavaScript

NB: Beware to have proper equals/hashCode for type T.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement