Fix bug in Utils.binarySearchLessThan

This commit is contained in:
Joel Therrien 2018-10-25 11:21:45 -07:00
parent ae91dbe9e7
commit a887a3cc15
2 changed files with 43 additions and 1 deletions

View file

@ -79,6 +79,10 @@ public final class Utils {
return endIndex - 1; return endIndex - 1;
} }
if(x[startIndex] > time){
return -1;
}
if(range < 200){ if(range < 200){
for(int i = startIndex; i < endIndex; i++){ for(int i = startIndex; i < endIndex; i++){
if(x[i] > time){ if(x[i] > time){
@ -90,7 +94,7 @@ public final class Utils {
// else // else
final int middle = range / 2; final int middle = startIndex + range / 2;
final double middleTime = x[middle]; final double middleTime = x[middle];
if(middleTime < time){ if(middleTime < time){
// go right // go right

View file

@ -7,6 +7,8 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.function.DoubleSupplier;
import java.util.stream.DoubleStream;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
@ -115,4 +117,40 @@ public class TestUtils {
} }
} }
@Test
public void testBinarySearchLessThan(){
/*
There was a bug where I didn't add startIndex to range/2 for middle; no other tests caught it!
*/
final int n = 10000;
double[] x = DoubleStream.generate(new DoubleSequenceGenerator()).limit(n).toArray();
for(int i = 0; i < n; i=i+100){
final int index = Utils.binarySearchLessThan(0, n, x, i);
final int indexOff = Utils.binarySearchLessThan(0, n, x, ((double) i) + 1.5);
assertEquals(i, index);
assertEquals(i+1, indexOff);
}
final int indexTooFar = Utils.binarySearchLessThan(0, n, x, n + 100);
assertEquals(n-1, indexTooFar);
final int indexTooEarly = Utils.binarySearchLessThan(0, n, x, -100);
assertEquals(-1, indexTooEarly);
}
private static class DoubleSequenceGenerator implements DoubleSupplier {
private double previous = 0.0;
@Override
public double getAsDouble() {
return previous++;
}
}
} }