G
G
gleendo2017-02-17 18:30:55
Java
gleendo, 2017-02-17 18:30:55

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();
    }
}

Now we need to write a merge method that will merge 2 intervals.
Usage:
for (int k : merge(interval(10, 12), interval(10, 12))) {
     System.out.print(k + " "); // 10 10 11 11
}

How now to implement this merge? The algorithm for merging two arrays is clear to me, but I can’t figure out how to write a merger of two intervals. Please advise how to implement the solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-02-17
@zagayevskiy

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 question

Ask a Question

731 491 924 answers to any question