All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.jnape.palatable.lambda.iterators.CombinatorialIterator Maven / Gradle / Ivy

There is a newer version: 5.5.0
Show newest version
package com.jnape.palatable.lambda.iterators;

import com.jnape.palatable.lambda.adt.hlist.Tuple2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

import static com.jnape.palatable.lambda.adt.hlist.HList.tuple;

public class CombinatorialIterator extends ImmutableIterator> {
    private final Iterator     asIterator;
    private final Iterator     bsIterator;
    private final ListIterator doublyLinkedBsIterator;
    private       A               currentA;

    public CombinatorialIterator(Iterator asIterator, Iterator bsIterator) {
        this.asIterator = asIterator;
        this.bsIterator = bsIterator;
        this.doublyLinkedBsIterator = new ArrayList().listIterator();
        currentA = null;
    }

    @Override
    public boolean hasNext() {
        return (moreAs() || currentA != null) && moreBs();
    }

    @Override
    public Tuple2 next() {
        if (currentA == null)
            currentA = asIterator.next();

        if (bsIterator.hasNext()) {
            doublyLinkedBsIterator.add(bsIterator.next());
            doublyLinkedBsIterator.previous();
        }

        Tuple2 tuple = tuple(currentA, doublyLinkedBsIterator.next());

        if (moreAs() && !moreBs()) {
            currentA = asIterator.next();
            while (doublyLinkedBsIterator.hasPrevious())
                doublyLinkedBsIterator.previous();
        }

        return tuple;
    }

    private boolean moreAs() {
        return asIterator.hasNext();
    }

    private boolean moreBs() {
        return bsIterator.hasNext() || doublyLinkedBsIterator.hasNext();
    }
}