开发者

How can I implement this Python snippet in Java?

I have this Python code that I found online and would like to know how to translate it to Java. My question is not about the algorithm but how to handle the function's arguments.

Here is the code:

def ternarySearch(f, left开发者_JAVA百科, right, absolutePrecision):
    #left and right are the current bounds; the maximum is between them
    if (right - left) < absolutePrecision:
        return (left + right)/2
 
    leftThird = (2*left + right)/3
    rightThird = (left + 2*right)/3
 
    if f(leftThird) < f(rightThird):
        return ternarySearch(f, leftThird, right, absolutePrecision)

    return ternarySearch(f, left, rightThird, absolutePrecision)

I would like to know what the function definition would look like. For example, a function returning y=x^2+3 would look like:

public static int y(int x){
 return x*x+3;
}

but

 return ternarySearch(f, leftThird, right, absolutePrecision)

is not working for me and I'd like to know what to do.

Update:

so for example i have y=3*x+2 it will be like this?

interface MyFunctor {
 int myFunction(int x);
}

class MyFunctorImpl implements MyFunctor {
  int myFunction(int  x) {
      return 3*x+2
  }
}

like this?


In Java, there are no higher-order functions. That is, you can't pass a function as an argument to another function. What you can do is use the Command pattern; define an Interface supporting the method that you need, then pass an instance of that Interface implementing the method.

For example:

int ternarySearch(MyFunctor f, int left, int right, float absolutePrecision) {
  #left and right are the current bounds; the maximum is between them
  if (right - left) < absolutePrecision:
    return (left + right)/2

  leftThird = (2*left + right)/3
  rightThird = (left + 2*right)/3

  if (f.myFunction(leftThird) < f.myFunction(rightThird)) {
    return ternarySearch(f, leftThird, right, absolutePrecision)
  }
  return ternarySearch(f, left, rightThird, absolutePrecision)
}

and

interface MyFunctor {
  int myFunction(int arg);
}

and

class MyFunctorImpl implements MyFunctor {
  int myFunction(int arg) {
     // implementation
  }
}

Then you could call ternarySearch with an instance of MyFunctorImpl as the first argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜