Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for datastructure that maintains a size & purges older elements in the process

Usecase maintain a list of the last n visited URLs (where n is a fix number). As new URLs are added to the list, older urls are removed automatically (in order to keep it at n elements)

Requirement The data structure needs to be sorted by time (should be no problem if it accepts a Comparator).

like image 272
Jacques René Mesrine Avatar asked Aug 06 '26 16:08

Jacques René Mesrine


2 Answers

You need a circular buffer.

Just keep an array b[] of size N and index k, that points to the oldest URL. Every time you need to add new URL, assign it to b[k] and increment k, wrapping it if needed: k = (k + 1) % N.

All your URLs will be naturally sorted, the oldest is at k, the second oldest at k+1, and so on, the newest is at k-1. (The sequence wraps at the end of the array).

like image 164
Igor Krivokon Avatar answered Aug 08 '26 11:08

Igor Krivokon


In java there are several implementation of Queue. It should be trivial to inherit or warp an existing implementation and implement the add() method like this:

boolean add(E e) {
  if(q.size()==MAX_SIZE) {
    remove();
  }
  q.add(e)
}
like image 37
David Rabinowitz Avatar answered Aug 08 '26 10:08

David Rabinowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!