import java.util.ArrayList;

/**
 * An example of using ArrayList and keeping it sorted.
 *
 * @author Zach Tomaszewski
 * @version 01 Apr 2008
 */
public class NumberList {

  private ArrayList<Integer> list;

  /**
   * Creates a number list containing "size" number of integers.
   * The list contains random integers between lowerRange and upperRange,
   * including both endpoints.  The list is sorted if specified.
   */
  public NumberList(int size, int lowerRange, int upperRange, boolean sorted) {
    list = new ArrayList<Integer>();
    //now load with random integers
    for (int n = 0; n < size; n++) {
      //XXX: didn't check if upperRange > lowerRange
      int nextInt = (int) (Math.random() * (upperRange - lowerRange + 1)) +
                          lowerRange;
      if (sorted) {
        //find where to insert into list
        int i = 0;
        while (i < list.size() && list.get(i) >= nextInt) {
          //loop through list until find the proper place to insert
          i++;
        }
        //now insert
        list.add(i, nextInt);

      }else {
        //just append to end of list
        list.add(nextInt);
      }
    }
  }

  /**
   * Returns the comma-separated contents of this list in [brackets].
   */
  public String toString() {
    String result = "[";
    //loop through list appending each item
    for (int i = 0; i < list.size(); i++) {
      result += list.get(i);
      if (i < list.size() - 1) {
        //add commas between items except for last
        result += ", ";
      }
    }
    result += "]";
    return result;
  }


  /**
   * Creates a few sample lists and prints them out.
   */
  public static void main(String[] args) {
    NumberList random = new NumberList(10, 1, 10, false);
    System.out.println("Random: " + random);

    NumberList sorted = new NumberList(10, 0, 100, true);
    System.out.println("Sorted: " + sorted);

    NumberList empty = new NumberList(0, 1, 10, true);
    System.out.println("Empty: " + empty);
  }

}
