java - Binary optimization search -
i'm trying write function optimize function using binary subdivision. idea can pass lower , upper bounds test , return lowest value of n returns 'true' function.
public interface binarytest { boolean test(int n); } /** * returns smallest int in set lower <= n <= upper returns true * {@link binarytest#test(int)}. if value 'n' returns true, value * > 'n' return true. * * if none of values return true, return -1. */ int optimizesmallest(int lower, int upper, binarytest testfunction) { // ??? }
while examples of binary search common, more difficult find patterns , feel it's easy end off-by-one error.
what optimizesmallest function like?
simple testcase:
(int = 0; < 10; i++) { int j = i; int r = binarysearch.optimizesmallest(0, 10, (n) -> { return n > j; }); assertequals(i + 1, r); }
int optimizesmallest(int lower, int upper, binarytest testfunction) { if (lower > upper || !testfunction.test(upper)) { return -1; } while (lower != upper) { int middle = (lower + upper) / 2; if (testfunction.test(middle)) { upper = middle; } else { lower = middle + 1; } } return lower; }
Comments
Post a Comment