Skip to content

Instantly share code, notes, and snippets.

@AL3X-69
Last active August 28, 2023 15:08
Show Gist options
  • Save AL3X-69/252c2377e071e98851a6bc7cbf77b4c8 to your computer and use it in GitHub Desktop.
Save AL3X-69/252c2377e071e98851a6bc7cbf77b4c8 to your computer and use it in GitHub Desktop.
Mathematic Interval java implementation
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.HashSet;
import java.util.Set;
public class Interval {
private final double left;
private final boolean leftInclusive;
private final double right;
private final boolean rightInclusive;
private final Set<Interval> excludedIntervals = new HashSet<>();
public Interval(double left, boolean leftInclusive, double right, boolean rightInclusive) {
this.left = left;
this.leftInclusive = leftInclusive;
this.right = right;
this.rightInclusive = rightInclusive;
}
@Contract(value = " -> new", pure = true)
public static @NotNull Interval reals() {
return new Interval(Double.NEGATIVE_INFINITY, true, Double.POSITIVE_INFINITY, true);
}
@Contract(value = "_ -> new", pure = true)
public static @NotNull Interval positives(boolean includeZero) {
return new Interval(0, includeZero, Double.POSITIVE_INFINITY, true);
}
@Contract(value = " -> new", pure = true)
public static @NotNull Interval positives() {
return Interval.positives(true);
}
@Contract(value = "_ -> new", pure = true)
public static @NotNull Interval negatives(boolean includeZero) {
return new Interval(Double.NEGATIVE_INFINITY, true, 0, includeZero);
}
@Contract(value = " -> new", pure = true)
public static @NotNull Interval negatives() {
return Interval.negatives(true);
}
public static @NotNull Interval fromTo(double from, double to, boolean inclusive) {
return new Interval(from, inclusive, to, inclusive);
}
public boolean includes(double n) {
return (leftInclusive ? left <= n : left < n)
&& (rightInclusive ? n <= right : n < right)
&& excludedIntervals.stream().noneMatch(interval -> interval.includes(n));
}
public Interval exclude(Interval interval) {
excludedIntervals.add(interval);
return this;
}
public Interval exclude(double n) {
return exclude(Interval.fromTo(n, n, true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment