Java 二进制优化搜索

Java 二进制优化搜索,java,optimization,binary-search,Java,Optimization,Binary Search,我正在尝试编写一个函数,使用二进制细分优化函数。我的想法是,我可以将上下限传递给它进行测试,它将返回从函数返回“true”的最低值n public interface BinaryTest { boolean test(int n); } /** * Returns the smallest int in the set lower <= n <= upper that returns true for * {@link BinaryTest#test(int)}. I

我正在尝试编写一个函数,使用二进制细分优化函数。我的想法是,我可以将上下限传递给它进行测试,它将返回从函数返回“true”的最低值n

public interface BinaryTest {
    boolean test(int n);
}

/**
 * Returns the smallest int in the set lower <= n <= upper that returns true for
 * {@link BinaryTest#test(int)}. If a value 'n' returns true, then any value
 * > 'n' will also return true.
 *
 * If none of the values return true, return -1.
 */
int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    // ???
}
公共接口二进制测试{
布尔检验(int-n);
}
/**
*返回集合下限中的最小整数Try:

这不是最优的(在某些情况下,它会再次测试最终值),但似乎对我抛出的所有测试用例都有效。我将把它留在这里,直到有人发布一个比这个更好的答案

public static int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    while (lower < upper) {
        int mid = (lower + upper) >>> 1;

        if (testFunction.test(mid))
            upper = mid;
        else
            lower = mid + 1;
    }

    return testFunction.test(lower) ? lower : -1;
}
publicstaticint(int-lower、int-upper、BinaryTest-testFunction){
while(下部<上部){
int mid=(下+上)>>>1;
if(testFunction.test(mid))
上=中;
其他的
下=中+1;
}
返回testFunction.test(较低)?较低:-1;
}

您仍然需要对该问题进行二进制搜索。只需确保最终的结果是您的
lower==upper-1
。在这种情况下,
testFunction.test(下)
返回false,
testFunction.test(上)
返回true。您将返回upper作为您的答案。当我在一个简单的testcase.Bingo上运行它时,会抛出一个StackOverflowException。这一个可行,但它与我上面给出的答案有相同的问题——在某些情况下,它会对最终答案进行两次测试。你认为有可能避免双重测试吗?示例:BinarySearch.OptimizeMinimum(0,10,(n)->{System.out.println(n);返回n>0;})@Sliphed现在它是最佳的-一旦我们确定答案不是-1,我们将只检查返回的整数一次。@Sliphed:我试图在wordpress论坛上与您联系,了解您启动的许可证软件管理器线程。是否有可能获得关于如何使用c应用程序激活许可证的c#示例。我一直没能让它工作。。。
int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    if(lower >= upper) {
        return upper;
    }
    int mid = (low + high) >>> 1;
    return testFunction.test(mid) ? optimizeSmallest(lower, mid, testFunction) 
        : optimizeSmallest(mid, upper, testFunction);
}
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;
}
public static int optimizeSmallest(int lower, int upper, BinaryTest testFunction) {
    while (lower < upper) {
        int mid = (lower + upper) >>> 1;

        if (testFunction.test(mid))
            upper = mid;
        else
            lower = mid + 1;
    }

    return testFunction.test(lower) ? lower : -1;
}