final DistanceResultPair<D> x = referenceDists.get(index);
final double xDist = x.getDistance().doubleValue();
int lef = index - 1;
int rig = index + 1;
Mean mean = new Mean();
double lef_d = (lef >= 0) ? referenceDists.get(lef).getDistance().doubleValue() : Double.NEGATIVE_INFINITY;
double rig_d = (rig < referenceDists.size()) ? referenceDists.get(rig).getDistance().doubleValue() : Double.NEGATIVE_INFINITY;
while(mean.getCount() < k) {
if(lef >= 0 && rig < referenceDists.size()) {
// Prefer n or m?
if(Math.abs(lef_d - xDist) < Math.abs(rig_d - xDist)) {
mean.put(Math.abs(lef_d - xDist));
// Update n
lef--;
lef_d = (lef >= 0) ? referenceDists.get(lef).getDistance().doubleValue() : Double.NEGATIVE_INFINITY;
}
else {
mean.put(Math.abs(rig_d - xDist));
// Update right
rig++;
rig_d = (rig < referenceDists.size()) ? referenceDists.get(rig).getDistance().doubleValue() : Double.NEGATIVE_INFINITY;
}
}
else {
if(lef >= 0) {
// Choose left, since right is not available.
mean.put(Math.abs(lef_d - xDist));
// update left
lef--;
lef_d = (lef >= 0) ? referenceDists.get(lef).getDistance().doubleValue() : Double.NEGATIVE_INFINITY;
}
else if(rig < referenceDists.size()) {
// Choose right, since left is not available
mean.put(Math.abs(rig_d - xDist));
// Update right
rig++;
rig_d = (rig < referenceDists.size()) ? referenceDists.get(rig).getDistance().doubleValue() : Double.NEGATIVE_INFINITY;
}
else {
// Not enough objects in database?
throw new IndexOutOfBoundsException();
}
}
}
return 1.0 / mean.getMean();
}