Check if the number is in the interval without using "if" or loops

So, I have a basic question. I could solve this easily, but now I am stunned because my teacher would like us to resolve this without using any statements or cycles. So the span is not an array. The main example is [1,6] or (1,6) or mixed, both open and closed. So 5 will be in the interval. I need a contains (double number) method that checks if the number is inside. How can you do this without an if or loop? I'm dumb? Is there some magic method that I have not stumbled upon?

My approach would be something like

public double contains(number)
{
    if (number >= leftEndPoint && number <= rightEndPoint) //lets assume interval is "closed" heh. on both ends
    return true;

    return false;

}

But ... We cannot use an if statement or a loop.

+4
source share
5

, if true false. , , if. ,

if (x)
    return true;
else
    return false;

return x;
+5

true false. , , if-statements:

public boolean contains(double number) {
    return number >= startNum && number <= endNum;
}

, , , startNum endNum -.

+2
if(x)
    return true;

. , , if (true) /* something */; if (isOn == true) /**/.

, :

return number >= leftEndPoint && number <= rightEndPoint;

.

+1

. , .

public class Interval {
  final int bottom;
  final int top;
  final IntervalEvaluationStrategy strategy;

  public Interval(final int bottom, final int top, final IntervalEvaluationStrategy strategy) {
    this.bottom = bottom;
    this.top = top;
    this.strategy = strategy;
  }

  public boolean check(int value) {
    return strategy.evaluate(value, bottom, top);
  }

  public enum IntervalEvaluationStrategy {
    OPEN {
      @Override
      boolean evaluate(int value, int bottom, int top) {
        return CLOSED.evaluate(value, bottom, top)
            || value == bottom
            || value == top;
      }
    },
    CLOSED {
      @Override
      boolean evaluate(int value, int bottom, int top) {
        return value > bottom
            && value < top;
      }
    };

    abstract boolean evaluate(int value, int bottom, int top);
  }

  public static void main(String[] args) {
    assert checkInterval(5, 5, 10, IntervalEvaluationStrategy.OPEN);
  }

  //helper method with example usage
  public static boolean checkInterval(final int value, final int bottom, final int top, IntervalEvaluationStrategy strategy) {
    final Interval interval = new Interval(bottom, top, strategy);
    return interval.check(value);
  }
}
0

You can also use the conditional operator. For example: return (number> = leftEndPoint && number <= rightEndPoint)? true: false;

-2
source

Source: https://habr.com/ru/post/1629264/


All Articles