// File: Molo.java
// Time-stamp: "2003-03-19 16:25:30 calvanes"
// Scopo: Molo: soluzione domanda 1

public class Molo {

  private String codice;
  private String[] posti;

  public Molo(String c, int numposti) {
    codice = c;
    posti = new int[numposti];
  }

  public int numPostiBarca() {
    return posti.length;
  }

  public boolean libero(int n) {
    if (n < 0 || n >= posti.length)
      throw new RuntimeException("Numero posto non valido");
    else
      return posti[n] == null;
  }

  public void assegnaPostoBarca(int n, String barca) {
    if (n < 0 || n >= posti.length)
      throw new RuntimeException("Numero posto non valido");
    else if (posti[n] != null)
      throw new RuntimeException("Posto " + n + " gia' occupato");
    else
      posti[n] = barca;
  }

  public void liberaPostoBarca(int n) {
    if (n < 0 || n >= posti.length)
      throw new RuntimeException("Numero posto non valido");
    else
      posti[n] = null;
  }

  public String dammiBarca(int n) {
    if (n < 0 || n >= posti.length)
      throw new RuntimeException("Numero posto non valido");
    else if (posti[n] == null)
      throw new RuntimeException("Posto " + n + " libero");
    else
      return posti[n];
  }

  public int dammiUnPostoLibero() {
    for (int i = 0; i < posti.length; i++)
      if (posti[i] == null) return i;
    return -1;
  }

  public void compattaBarche() {
    int k = 0;
    for (int i = 0; i < posti.length; i++)
      if (posti[i] != null && i != k) {
        posti[k] = posti[i];
        posti[i] = null;
        k++;
      }
  }
}
