Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to compare time sequence in forward/reverse order

Tags:

java

Say my comparator function foo takes a time sequence as input, which could be a series of time from small to large, or from large to small.

Foo may look like this:

Foo(List<double> timestampList) {
  if (currentTime > previousMaxValueTimestamp) {
    ...
  } else if (curremtTime > previousMinValueTimestamp) {
    ...
  }
}

The above works for forward sequence, but not the reverse one. How can I elegantly write a logic that works for both types of sequence? Below is what I want to do, but it duplicates most of the code, which is not desired.

Foo(List<double> timestampList, boolean isForward) {
  if (isForward) {
        if (currentTime > previousMaxValueTimestamp) {
            ...
        } else if (curremtTime > previousMinValueTimestamp) {
            ...
        }
  } else {
        if (currentTime < previousMaxValueTimestamp) {
            ...
        } else if (curremtTime < previousMinValueTimestamp) {
            ...
        }
  }
}

My current solution is like below. Is it good coding style?

Foo(List<double> timestampList, boolean isForward) {
    if ((isForward && currentTime > previousMaxValueTimestamp) || (!isForward && currentTime < previousMaxValueTimestamp)) {
        ...
    } else if ((isForward && curremtTime < previousMinValueTimestamp) || (!isForward && currentTime > previousMaxValueTimestamp)) {
        ...
    }
}
like image 209
Stan Avatar asked Feb 09 '23 14:02

Stan


2 Answers

I don't know if something like this will still satisfy you, but in this way you can still reduce more or less your structure and you will not get this inflated code

if (isForward ? currentTime > previousMaxValueTimestamp :
    currentTime < previousMaxValueTimestamp)
{

} else if (!isForward ? currentTime < previousMaxValueTimestamp :
           currentTime < previousMinValueTimestamp)
{

}
like image 59
Lukas Hieronimus Adler Avatar answered Feb 16 '23 04:02

Lukas Hieronimus Adler


If you have the list sorted as i suspect you do, you can simply use an iterator :

ListIterator li = a.listIterator(a.size());
while(isForward ? li.hasPrevious() : li.hasNext()) {
  nextItem = isForward ? li.previous() : li.next());
  //do stuff

}

taken from here and then edited to fit your needs

if your items are not pre-sorted and you can live with the pre-sorting overhead, you may use Collections.sort(yourList,yourSpecialComparator) providing your own special comparator.

like image 20
Ofek Ron Avatar answered Feb 16 '23 03:02

Ofek Ron