// File: Wardrobe.java
// Time-stamp: "2005-01-09 17:54:13 calvanese"
// Scopo: Wardrobe: solution part 1

public class Wardrobe {

  // representation of the objects
  /*
    Note that the information associated to a hook consists of two parts:
      - whether the hooks is free or occupied
      - the clothing item on the hook, when the hook is occupied

    Since the item is represented by a string (i.e., a reference to an object
    of type String), it is possible to use the special value null to represent
    the fact that a hook is free.  Hence, in this case, both parts of the
    information associated to a hook can be represented by means of a single
    value of type String.

    In general, however, this is not always possible.  See the alternative
    solution, in which the two parts of the information associated to a hook
    are represented separately by making use of an auxiliary class.
  */

  private String[] hooks;

  // pubblic methods

  public Wardrobe(int n) {
    hooks = new String[n];
  }

  public int getNumHooks() {
    return hooks.length;
  }

  public int assignHook(String c) {
    for (int i = 0; i < hooks.length; i++)
      if (hooks[i] == null) {
        hooks[i] = c;
        return i;
      }
    return -1;
  }

  public void emptyHook(int n) {
    if (n >= 0 && n < hooks.length)
      hooks[n] = null;
  }

  public String getItem(int n) {
    if (n >= 0 && n < hooks.length)
      return hooks[n];
    else
      return null;
  }

  public int searchItem(String c) {
    for (int i = 0; i < hooks.length; i++)
      if (hooks[i] != null && hooks[i].equals(c)) return i;
    return -1;
  }

  public int getNumOccupiedHooks() {
    int count = 0;
    for (int i = 0; i < hooks.length; i++)
      if (hooks[i] != null) count++;
    return count;
  }

  public void reorderWardrobe() {
    int firstEmpty = -1;  // index of the first empty hook
    for (int i = 0; i < hooks.length; i++) {
      if (hooks[i] == null && firstEmpty == -1)
        firstEmpty = i;
      if (hooks[i] != null && firstEmpty != -1) {
        hooks[firstEmpty] = hooks[i];
        hooks[i] = null;
        firstEmpty++;
      }
    }
  }
}
