Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I represent integer intervals in Java?

Tags:

java

We all know about intervals in mathematics (e.g -4 < x < 3).

How can I represent these mathematic intervals in Java, e.g, the numbers between -4 and 3 (-4, -3, ..., 2, 3 etc)?

like image 340
iSun Avatar asked Dec 03 '11 15:12

iSun


People also ask

How do you represent intervals in Java?

Check apache commons-lang IntRange . So, if you want to check if a number is in a given interval (range), you do: IntRange range = new IntRange(-4, 3); if (range. contains(x)) { .... }

What is an integer interval?

An integer interval [a,b], a < b, is a set of all consecutive integers beginning with a and ending with b. Write a program that: finds the minimal number of elements in a set containing at least two different integers from each interval. The first line of the input contains the number of intervals n, 1 <= n <= 10000.

What is interval class in Java?

An interval represents the time on the time-line between two Instant s. The class stores the start and end instants, with the start inclusive and the end exclusive. The end instant is always greater than or equal to the start instant. The Duration of an interval can be obtained, but is a separate concept.

How do you check if a value is between two numbers in Java?

To check if a number is between two numbers: Use the && (and) operator to chain two conditions.


2 Answers

Check apache commons-lang IntRange. So, if you want to check if a number is in a given interval (range), you do:

IntRange range = new IntRange(-4, 3);
if (range.contains(x)) {
   ....
}
like image 100
Bozho Avatar answered Sep 24 '22 22:09

Bozho


Google Guava also has a Range class (https://guava.dev/releases/19.0/api/docs/com/google/common/collect/Range.html) that may work for you.

like image 36
tperrigo Avatar answered Sep 26 '22 22:09

tperrigo