// File: Buffer.java
// Time-stamp: "2007-01-29 12:30:14 calvanese"
// Purpose: Buffer: solution part 1


public class Buffer {

  // representation of the objects

  // Note: by the way items are added and extracted, the buffer will alwaye
  // be full up to a certain position, and the remaining positions will be
  // empty;  therefore, to represent the buffer, it is sufficient to use an
  // array of integers, and an integer representing the number of items in the
  // buffer;

  private int numItems;
  private float[] positions;

  // public methods

  public Buffer(int c) {
    positions = new float[c];
    numItems = 0;
  }

  public int remainingCapacity() {
    return positions.length - numItems;
  }

  public int numDataItems() {
    return numItems;
  }

  public void addDataItem(float f) {
    if (numItems < positions.length) {
      positions[numItems] = f;
      numItems++;
    }
  }

  public float extractDataItem(int i) {
    float res = 0;
    if (i < 0 || i >= numItems)
      System.out.println("Index out of range");
    else {
      res = positions[i];
      for (int j = i; j < numItems-1; j++)
        positions[j] = positions[j+1];
      numItems--;
    }
    return res;
  }
   
  public int countOccurrences(float f) {
    int num = 0;
    for (int i = 0; i < numItems; i++)
      if (positions[i] == f)
        num++;
    return num;
  }

  public int[] whichPositions(float f) {
    int[] res = new int[countOccurrences(f)];
    int next = 0;
    for (int pos = 0; pos < numItems; pos++)
      if (positions[pos] == f) {
        res[next] = pos;
        next++;
      }
    return res;
  }

}
