Skip to content

Instantly share code, notes, and snippets.

@SleimanJneidi
Created February 25, 2020 16: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 SleimanJneidi/4e26c5753583920fb292326614f91d57 to your computer and use it in GitHub Desktop.
Save SleimanJneidi/4e26c5753583920fb292326614f91d57 to your computer and use it in GitHub Desktop.
static class RangeSet extends AbstractSet<Integer> {
static class Interval {
private final int start;
private final int end;
Interval(int start, int end) {
this.start = start;
this.end = end;
}
boolean contains(int value) {
return value >= start && value <= end;
}
int size() {
return (end - start) + 1;
}
@Override
public String toString() {
return "Interval{" +
"start=" + start +
", end=" + end +
'}';
}
}
private final Collection<Interval> intervals;
RangeSet(Collection<Interval> intervals) {
this.intervals = intervals;
}
@Override
public Iterator<Integer> iterator() {
int size = this.size();
Iterator<Interval> intervalIterator = intervals.iterator();
return new Iterator<Integer>() {
int currentPointer = 0;
Interval currentInterval = intervalIterator.hasNext() ? intervalIterator.next() : null;
int current = currentInterval != null ? currentInterval.start : -1;
@Override
public boolean hasNext() {
return currentPointer < size;
}
@Override
public Integer next() {
int currentValue = current;
if(currentValue == currentInterval.end && intervalIterator.hasNext()) {
currentInterval = intervalIterator.next();
current = currentInterval.start;
} else {
current++;
}
currentPointer++;
return currentValue;
}
};
}
@Override
public int size() {
return intervals.stream().mapToInt(Interval::size)
.sum();
}
@Override
public boolean contains(Object o) {
if(o == null){
return false;
}
int value = (int)o;
for (Interval interval : intervals) {
if(interval.contains(value)){
return true;
}
}
return false;
}
@Override
public boolean add(Integer integer) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends Integer> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment