Princeton Algorithm Part 1 Week - Brute ii

//重写了Brute

package PA3;

import java.util.ArrayList;
import java.util.Arrays;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;


public class BruteCollinearPoints {
    private int segNum; //number of segments;
    private ArrayList segTemp = new ArrayList();
    // temp, with null segments;
    private LineSegment[] result;
    
    public BruteCollinearPoints(Point[] points){
        Arrays.sort(points, new Point(0,0).slopeOrder());
        int size = points.length;
        for (int i = 0; i < size; i++){
            for (int j = i+1; j < size; j++){
                for (int k = j+1; k < size; k++){
                    for (int l = k+1; l < size; l++){
                        if (points[i].slopeTo(points[j])
                                == points[i].slopeTo(points[k])
                                && points[i].slopeTo(points[k])
                                == points[i].slopeTo(points[l]))
                        {
                            points[i].drawTo(points[l]);
                            segTemp.add(new LineSegment(points[i],points[l]));
                            segNum++;
                        }
                    }
                }
            }
        }
        result = new LineSegment[segNum];
        for (int i = 0; i < segNum; i++){
            result[i] = segTemp.get(i);
        }
    }
    
    public int numberOfSegments(){
        return segNum;
    }
    
    public LineSegment[] segments(){
        return result;
    }
    
    public static void main(String[] args){
        StdDraw.setXscale(0,32768);
        StdDraw.setYscale(0,32768);
        
        String filename = args[0];
        In in = new In(filename);
        int N = in.readInt();
        Point[] pointArray = new Point[N];
        for (int i = 0; i < N; i++){
            int x = in.readInt();
            int y = in.readInt();
            Point p = new Point(x,y);
            pointArray[i] = p;
            p.draw();
        }
        BruteCollinearPoints BCP = new BruteCollinearPoints(pointArray);
    }
}

你可能感兴趣的:(Princeton Algorithm Part 1 Week - Brute ii)