/* ClosestPair.java
 * CS 136 Spring 2007
 * Tutorial 11: File I/O and Java Arrays
 */

/* This class contains one public method, find, which finds the
 * closest pair of array entries which are equal.
 */
public class ClosestPair {
  
  /* Finds the closest pair of equal array entries. If such a pair
   * exists, the subarray with the two equal entries as the start
   * and end elements is returned.
   * pre: array != null
   * return: The subarray between the two closest entries, or null
   *         if there are no two equal entries in the array.
   */
  public static int[] find(int[] array) {
    for( int dist = 1; dist <= array.length-1; ++dist ) {
      for( int start = 0; start + dist < array.length; ++start ) {
        if( array[start] == array[start+dist] ) {
	  return makeSubArray(array, start, start+dist);
        }
      }
    }
    return null;
  }

  /* Helper method for find to get a subarray between the given indices.
   * pre: array != null, 0 <= start <= end < array.length
   * return: A new array with length (end-start+1) filled with
   *         the entries in array from index start to index end.
   */
  private static int[] makeSubArray(int[] array, int start, int end) {
    int[] sub = new int[end-start+1];
    for( int i = start; i <= end; ++i )
      sub[i-start] = array[i];
    return sub;
  }
}
