Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
2.2 kB
3
Indexable
Never
package com.comp301.a05driver;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SnakeOrderAcrossPoolsIterator implements Iterator<Driver> {

  private final List<Iterator<Driver>> driverPoolsCollection;
  private Driver nextDriver;
  private int size;
  private int tracker;
  private int i;
  private boolean up;

  public SnakeOrderAcrossPoolsIterator(List<Iterable<Driver>> driverPools) {
    driverPoolsCollection = new ArrayList<>();
    List<Iterator<Driver>> driverPoolsCollectionClone = new ArrayList<>();
    up = true;
    for (Iterable<Driver> driverPool : driverPools) {
      if (driverPool == null) {
        throw new IllegalArgumentException("Driver pool is null");
      }
      driverPoolsCollection.add(driverPool.iterator());
      driverPoolsCollectionClone.add(driverPool.iterator());
    }
    nextDriver = null;
    for (Iterator<Driver> drivers : driverPoolsCollectionClone) {
      while (drivers.hasNext()) {
        drivers.next();
        size++;
      }
    }
  }

  private void loadNextDriver() {
    if (nextDriver == null) {
      while (tracker != size) {
        while (!driverPoolsCollection.get(i).hasNext()) {
          while (!driverPoolsCollection.get(i).hasNext() && up) {
            i++;
            try {
              Iterator<Driver> test = driverPoolsCollection.get(i);
            } catch (Exception e) {
              i--;
              up = false;
            }
          }
          while (!driverPoolsCollection.get(i).hasNext() && !up) {
            i--;
            if (i == -1) {
              i++;
              up = true;
            }
          }
        }
        nextDriver = driverPoolsCollection.get(i).next();
        tracker++;
        return;
      }
    }
  }

  @Override
  public boolean hasNext() {
    if (tracker == size) {
      return false;
    }
    loadNextDriver();
    return true;
  }

  @Override
  public Driver next() {
    if (hasNext()) {
      Driver driver = nextDriver;
      nextDriver = null;
      return driver;
    } else {
      return nextDriver;
    }
  }
}