/**
 * An "infinitely large array" of integers; the backing buffer 
 * automatically resizes itself as new values are added.
 */
public class ResArray {
	
  private int[] data = {};
  private int extent = 0;
  
  /** Constructor, takes no arguments. */
  public ResArray() { 
  } 
  
  /** access the array at position i. If position i has not yet 
   * been initialized, return 0.
   *
   * @param i - index into the array
   * @return value of the array at that index
   */
  public int get(int i) {
	  if (i >= data.length) {
        return 0;
	  } else {
		return data[i];
	  }
   
  }

  /** Modify the array at position i to contain the value v. 
   * 
   * @param i - index
   * @param v - new value */
  public void set(int i, int v) { 
	  if (i >= data.length) {
		  // calculate newsize using the Java library static method max.
		  int newsize = Math.max(i+1, data.length * 2);
		  
		  int[] newdata = new int[newsize];
		  for (int j=0; j < data.length; j++){
			  newdata[j] = data[j];
		  }
		  this.data = newdata;
	  }
	
	  
	  data[i] = v;
	  
	  if (i >= extent && v != 0) {
		  extent = i + 1;
	  }
	  if (v == 0 && i + 1 == extent ) {
		  shrinkExtent(i);
	  }
  }
  
  private void shrinkExtent(int i) {
	  int j = i;
	  while (j >= 0 && data[j] == 0) {
	    j--;
	  }
	  extent = j+1;
  }
  
  
  /** the "extent" is the size of an array that would be 
   * necessary to store the smallest prefix
   * that contains all of the nonzero data. 
   * @return extent
   */
  public int getExtent() {
	  return extent; 
	  
  }
  
  /** Return the smallest prefix of the ResArray
   * that contains all of the nonzero values as a normal array. 
   * 
   * @return an array containing the values, a copy of the internal data.
   */
  public int[] values() {
	  return null; 
	  // TODO: this is a stub
  }
}
