Untitled

mail@pastecode.io avatar
unknown
java
2 years ago
2.8 kB
2
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;
  private int edge;

  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 (!driverPoolsCollection.get(i).hasNext()) {
        while (!driverPoolsCollection.get(i).hasNext() && up) {
          i++;
          if (i == driverPoolsCollection.size()) {
            i--;
            up = false;
          }
        }
        while (!driverPoolsCollection.get(i).hasNext() && !up) {
          i--;
          if (i == -1) {
            i++;
            up = true;
          }
        }
      }
      nextDriver = driverPoolsCollection.get(i).next();
      tracker++;
      if (driverPoolsCollection.size() == 1) {

      } else {
        if (up && i < driverPoolsCollection.size() - 1) {
          i++;
          return;
        }
        if (!up && i > 0) {
          i--;
          return;
        }
        if (up && i == driverPoolsCollection.size() - 1 && edge == 0) {
          edge++;
          return;
        }
        if (up && i == driverPoolsCollection.size() - 1 && edge == 1) {
          i--;
          edge = 0;
          up = false;
          return;
        }
        if (!up && i == 0 && edge == 0) {
          edge++;
          return;
        }
        if (!up && i == 0 && edge == 1) {
          i++;
          edge = 0;
          up = true;
          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;
    }
  }
}