// File: Wardrobe.java
// Time-stamp: "2005-01-09 18:06:11 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;
      }
    throw new RuntimeException("No empty hook");
  }

  public void emptyHook(int n) {
    if (n >= 0 && n < hooks.length)
      hooks[n] = null;
    else
      throw new RuntimeException("Hook number out of range");
  }
  
  public String getItem(int n) {
    if (n >= 0 && n < hooks.length)
      return hooks[n];
    else
      throw new RuntimeException("Hook number out of range");
  }

  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 addHooks(int n) {
    if (n <= 0)
      throw new RuntimeException("Number of hooks to add must be positive");

    String[] newHooks = new String[hooks.length + n];
    for (int i = 0; i < hooks.length; i++)
      newHooks[i] = hooks[i];
    hooks = newHooks;
  }

  public void reorderWardrobe() {
    String[] newHooks = new String[getNumOccupiedHooks()];
    int k = 0;
    for (int i = 0; i < hooks.length; i++)
      if (hooks[i] != null) {
        newHooks[k] = hooks[i];
        k++;
      }
    hooks = newHooks;
  }
}
