I'm working in Java and I have a list of objects of type TimestampAndValue:
public class TimestampAndValue{
private double value;
private long timestamp;
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
}
My list is similar to this:
And I want to have this list in output:
I'll try to explain what I need in short. When two timestamps aren't contiguous integers, I need to place the minimum number of zeros between them. For example in the case between the timestamp 4 and 6 in the above list I need to place only one zero, but in the case in which two timestamps differ by two or more I need to place a zero right after the first timestamp and a zero immediately before the second timestamp. You can see this in the case between timestamp 6 and 10. I need also that the placed zeros have the correct timestamp set.
For now I can't figure out how to solve it. Thank you for your support!
This is the solution which worked for me using your suggestions:
public static List<TimestampAndValue> insertMinimumNumberOfZerosBetweenValues(List<TimestampAndValue> list){
if(list == null || list.isEmpty() || list.size() == 1)
return list;
int i;
int j;
long tempTimestamp1;
long tempTimestamp2;
long timestampDifference;
List<TimestampAndValue> outList = new ArrayList<TimestampAndValue>();
outList.add(list.get(0));
for(i=0; i<list.size()-1; i++){
j=i+1;
tempTimestamp1 = list.get(i).getTimestamp();
tempTimestamp2 = list.get(j).getTimestamp();
timestampDifference = tempTimestamp2 - tempTimestamp1;
if(timestampDifference == 2){
TimestampAndValue tav = new TimestampAndValue();
tav.setTimestamp(tempTimestamp1 + 1);
tav.setValue(0);
outList.add(tav);
}
else if(timestampDifference > 2){
TimestampAndValue tav = new TimestampAndValue();
tav.setTimestamp(tempTimestamp1 + 1);
tav.setValue(0);
outList.add(tav);
TimestampAndValue tav2 = new TimestampAndValue();
tav2.setTimestamp(tempTimestamp2 - 1);
tav2.setValue(0);
outList.add(tav2);
}
outList.add(list.get(j));
}
return outList;
}
You have to process pairs of timestamps from the input list, accumulating an output list:
outputList = new list of timestamps;
for (int i = 0; i < numerOfTimestamps-1; i++) {
timestamp1 = inputList.get(i);
timestamp2 = inputList.get(i+1);
For each pair compare the distance between them:
timestamp1
to output listtimestamp1
and a new timestamp with 0
to output listtimestamp1
and two new timestamps with 0
to output listThen
} // close loop
and add the last timestamp to the output list. (It's never added by the loop.)
Note that you need to treat the empty input list separately.