import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;

/**
 * A list of line segments stored in ascending order by length.
 *
 * @author Drue Coles
 */
public class SortedListOfLineSegments {

    private final ArrayList<LineSegment> lineSegments;

    /**
     * Creates an empty list of line segments.
     */
    public SortedListOfLineSegments() {
        lineSegments = new ArrayList<>();
    }

    /**
     * Returns the size of this list.
     */
    public int size() {
        return lineSegments.size();
    }

    /**
     * Returns the line segment at a given position in this list.
     */
    public LineSegment get(int i) {
        return lineSegments.get(i);
    }

    /**
     * Adds a line segment to the list at its correct position in length order.
     */
    public void add(LineSegment ls) {
        int i = 0; // position at which to insert
        double length = ls.length();

        while (i < size()) {
            double otherLength = get(i).length();
            if (length <= otherLength) {
                break;
            }
            i++;
        }

        lineSegments.add(i, ls);
    }

    /**
     * Test program that adds ten line segments with random endpoints to a list
     * and then traverses the list to verify that the objects are stored in length order.
     */
    public static void main(String[] args) {

        SortedListOfLineSegments lineSegments = new SortedListOfLineSegments();
        ThreadLocalRandom rand = ThreadLocalRandom.current();
        final int NUM_LINE_SEGMENTS = 10;
        for (int i = 0; i < NUM_LINE_SEGMENTS; i++) {
            // random coordinates for two endpoints
            double a = rand.nextDouble(0, 10);
            double b = rand.nextDouble(0, 10);
            double u = rand.nextDouble(0, 10);
            double v = rand.nextDouble(0, 10);
            lineSegments.add(new LineSegment(a, b, u, v));
        }

        // output contents of list to verify order
        for (int i = 0; i < lineSegments.size(); i++) {
            System.out.println(lineSegments.get(i));
        }
    }
}