Skip to content

Instantly share code, notes, and snippets.

@ymnk
Last active December 21, 2015 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymnk/6294349 to your computer and use it in GitHub Desktop.
Save ymnk/6294349 to your computer and use it in GitHub Desktop.
class Interval {
private Point upper;
private Point lower;
private Interval(Point lower, Point upper) {
if (lower != infinite && upper != infinite
&& !inclusive(lower.p).greater(upper.p))
throw new IllegalArgumentException(lower + " " + upper);
this.lower = lower;
this.upper = upper;
}
public String toString() {
return ((lower instanceof Inclusive) ? "[" : "(") + lower + "," + upper
+ ((upper instanceof Inclusive) ? "]" : ")");
}
static abstract class Point {
Comparable p;
abstract boolean less(Comparable i);
abstract boolean greater(Comparable i);
public String toString() {
return p.toString();
}
}
private static class Inclusive extends Point {
Inclusive(Comparable p) {
this.p = p;
}
boolean less(Comparable i) {
return p.compareTo(i) >= 0;
}
boolean greater(Comparable i) {
return p.compareTo(i) <= 0;
}
}
private static class Exclusive extends Point {
Exclusive(Comparable p) {
this.p = p;
}
boolean less(Comparable i) {
return p.compareTo(i) > 0;
}
boolean greater(Comparable i) {
// return p < i;
return p.compareTo(i) < 0;
}
}
static Point infinite = new Point() {
boolean less(Comparable i) {
return true;
}
boolean greater(Comparable i) {
return true;
}
public String toString() {
return "∞";
}
};
static Point inclusive(Comparable i) {
return new Inclusive(i);
}
static Point exclusive(Comparable i) {
return new Exclusive(i);
}
boolean contains(Comparable i) {
return lower.greater(i) && upper.less(i);
}
boolean containsAll(Comparable[] list) {
for (int i = 0; i < list.length; i++) {
if (!contains(list[i]))
return false;
}
return true;
}
static Interval OpenCloseInterval(Comparable u, Comparable p) {
return new Interval(exclusive(u), inclusive(p));
}
static Interval OpenOpenInterval(Comparable u, Comparable p) {
return new Interval(exclusive(u), exclusive(p));
}
static Interval CloseCloseInterval(Comparable u, Comparable p) {
return new Interval(inclusive(u), inclusive(p));
}
static Interval CloseOpenInterval(Comparable u, Comparable p) {
return new Interval(inclusive(u), exclusive(p));
}
static Interval LeftOpenInterval(Comparable u) {
return new Interval(exclusive(u), infinite);
}
static Interval LeftCloseInterval(Comparable u) {
return new Interval(inclusive(u), infinite);
}
static Interval RightOpenInterval(Comparable u) {
return new Interval(infinite, exclusive(u));
}
static Interval RightCloseInterval(Comparable u) {
return new Interval(infinite, inclusive(u));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment