PointSET.java 2.09 KB
import java.io.BufferedReader;
import java.io.FileReader;

import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.Point2D;
import edu.princeton.cs.algs4.RectHV;
import edu.princeton.cs.algs4.SET;

public class PointSET {

	private SET<Point2D> points;

	// construct an empty set of points
	public PointSET() {
		this.points = new SET<Point2D>();
	}

	// is the set empty?
	public boolean isEmpty() {
		return points.isEmpty();
	}

	// number of points in the set
	public int size() {
		return points.size();
	}

	// add the point to the set (if it is not already in the set)
	public void insert(Point2D p) {

		if(p == null)
			throw new NullPointerException();
		
		if (!points.contains(p)) {
			points.add(p);
		}
	}

	// does the set contain point p?
	public boolean contains(Point2D p) {
		
		if(p == null)
			throw new NullPointerException();
		
		return points.contains(p);
	}

	// draw all points to standard draw
	public void draw() {
		for (Point2D p : points) {
			p.draw();
		}
	}

	// all points that are inside the rectangle
	public Iterable<Point2D> range(RectHV rect) {
		SET<Point2D> contains = new SET<Point2D>();

		for (Point2D p : points) {
			if (rect.contains(p)) {
				contains.add(p);
			}
		}

		return contains;
	}

	// a nearest neighbor in the set to point p; null if the set is empty
	public Point2D nearest(Point2D p) {

		Point2D closest = null;

		for (Point2D point : points) {

			if (closest == null || p.distanceTo(point) < p.distanceTo(closest)) {
				closest = p;
			}

		}

		return closest;
	}

	// unit testing of the methods (optional)
	public static void main(String[] args) throws Exception{
		
		PointSET set = new PointSET();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(args[0]));
		} catch (Exception e) {
			System.out.println("File not found");
		}
		
		String line;
		while((line = reader.readLine()) != null){
			String [] splitLine = line.trim().split("\\s+");
			
			double a = Double.parseDouble(splitLine[0]);
			double b = Double.parseDouble(splitLine[1]);
			Point2D p = new Point2D(a,b);
			set.insert(p);
		}
		
		set.draw();
		
	}
}