Answer the question
In order to leave comments, you need to log in
How to merge two Iterable intervals?
There is an interval method that returns the interval [left, right).
class IteratorUtils {
public static Iterable<Integer> interval(int left, int right) {
return new IntervalIterable(left, right);
}
public static Iterable<Integer> merge(Iterable<Integer> iter0, Iterable<Integer> iter1) {
// some code
}
}
class IntervalIterable implements Iterable<Integer> {
private final int left;
private final int right;
public IntervalIterable(int left, int right) {
this.left = left;
this.right = right;
}
@Override
public Iterator<Integer> iterator() {
return new IntervalIterator(left, right);
}
}
class IntervalIterator implements Iterator<Integer> {
private final int max;
private int current;
public IntervalIterator(int left, int right) {
this.max = right;
this.current = left;
}
public boolean hasNext() {
return current < max;
}
public Integer next() {
return current++;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
for (int k : merge(interval(10, 12), interval(10, 12))) {
System.out.print(k + " "); // 10 10 11 11
}
Answer the question
In order to leave comments, you need to log in
Everything is the same - you implement Iterable, which returns an Iterator, for which you implement next and hasNext. The Iterator must store two other iterators that d next/hasNext will interrogate in turn.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question