[3836] | 1 | // License: GPL. For details, see LICENSE file.
|
---|
| 2 | package org.openstreetmap.josm.gui.mappaint;
|
---|
| 3 |
|
---|
| 4 | /**
|
---|
| 5 | * An interval of the form "lower < x <= upper" where 0 <= lower < upper.
|
---|
| 6 | * (upper can be Double.POSITIVE_INFINITY)
|
---|
| 7 | * immutable class
|
---|
| 8 | */
|
---|
| 9 | public class Range {
|
---|
| 10 | private double lower;
|
---|
| 11 | private double upper;
|
---|
| 12 |
|
---|
| 13 | public Range() {
|
---|
| 14 | this.lower = 0;
|
---|
| 15 | this.upper = Double.POSITIVE_INFINITY;
|
---|
| 16 | }
|
---|
| 17 |
|
---|
| 18 | public Range(double lower, double upper) {
|
---|
| 19 | if (lower < 0 || lower >= upper)
|
---|
| 20 | throw new IllegalArgumentException();
|
---|
| 21 | this.lower = lower;
|
---|
| 22 | this.upper = upper;
|
---|
| 23 | }
|
---|
| 24 |
|
---|
| 25 | public boolean contains(double x) {
|
---|
| 26 | return lower < x && x <= upper;
|
---|
| 27 | }
|
---|
| 28 |
|
---|
| 29 | /**
|
---|
| 30 | * provides the intersection of 2 overlapping ranges
|
---|
| 31 | */
|
---|
| 32 | public static Range cut(Range a, Range b) {
|
---|
| 33 | if (b.lower >= a.upper || b.upper <= a.lower)
|
---|
| 34 | throw new IllegalArgumentException();
|
---|
| 35 | return new Range(Math.max(a.lower, b.lower), Math.min(a.upper, b.upper));
|
---|
| 36 | }
|
---|
| 37 |
|
---|
| 38 | /**
|
---|
| 39 | * under the premise, that x is within this range,
|
---|
| 40 | * and not within the other range, it shrinks this range in a way
|
---|
| 41 | * to exclude the other range, but still contain x.
|
---|
| 42 | *
|
---|
| 43 | * x |
|
---|
| 44 | *
|
---|
| 45 | * this (------------------------------]
|
---|
| 46 | *
|
---|
| 47 | * other (-------] or
|
---|
| 48 | * (-----------------]
|
---|
| 49 | *
|
---|
| 50 | * result (----------------]
|
---|
| 51 | */
|
---|
| 52 | public Range reduceAround(double x, Range other) {
|
---|
| 53 | if (!contains(x))
|
---|
| 54 | throw new IllegalArgumentException();
|
---|
| 55 | if (other.contains(x))
|
---|
| 56 | throw new IllegalArgumentException();
|
---|
| 57 |
|
---|
| 58 | if (x < other.lower && other.lower < upper)
|
---|
| 59 | return new Range(lower, other.lower);
|
---|
| 60 |
|
---|
| 61 | if (this.lower < other.upper && other.upper < x)
|
---|
| 62 | return new Range(other.upper, this.upper);
|
---|
| 63 |
|
---|
| 64 | return this;
|
---|
| 65 | }
|
---|
| 66 |
|
---|
| 67 | public double getLower() {
|
---|
| 68 | return lower;
|
---|
| 69 | }
|
---|
| 70 |
|
---|
| 71 | public double getUpper() {
|
---|
| 72 | return upper;
|
---|
| 73 | }
|
---|
| 74 |
|
---|
| 75 | @Override
|
---|
| 76 | public String toString() {
|
---|
| 77 | return String.format("|s%s-%s", lower, upper);
|
---|
| 78 | }
|
---|
| 79 | }
|
---|