// File: Pier.java
// Time-stamp: "2005-01-22 10:56:50 calvanese"
// Purpose: Pier: solution part 1

public class Pier {

  // representation of the objects
  private String code;
  private String[] positions;

  // public methods

  public Pier(String c, int numpositions) {
    code = c;
    positions = new String[numpositions];
  }

  public int numBoatPositions() {
    return positions.length;
  }

  public boolean isFree(int n) {
    if (n < 0 || n >= positions.length) {
      System.out.println("Boat position is not valid.");
      return false;
    } else
      return positions[n] == null;
  }

  public void assignPosition(int n, String boat) {
    if (n >= 0 && n < positions.length && positions[n] == null)
      positions[n] = boat;
  }

  public void freePosition(int n) {
    if (n >= 0 && n < positions.length)
      positions[n] = null;
  }

  public String getBoat(int n) {
    if (n >= 0 && n < positions.length)
      return positions[n];
    else
      return null;
  }

  public int getFreePosition() {
    for (int i = 0; i < positions.length; i++)
      if (positions[i] == null) return i;
    return -1;
  }

  public boolean searchHomonyms() {
    for (int i = 0; i < positions.length; i++)
      for (int j = i+1; j < positions.length; j++)
        if (positions[i] != null && positions[j] != null &&
            positions[i].equals(positions[j]))
          return true;
    return false;
  }

  public void compactBoats() {
    int k = 0;
    for (int i = 0; i < positions.length; i++)
      if (positions[i] != null) {
        if (k != i) {
          positions[k] = positions[i];
          positions[i] = null;
        }
        k++;
      }
  }
}
