summaryrefslogtreecommitdiffstats
path: root/Algorithms/Part-I/3-Collinear/Brute.java
blob: d7eb052fa196dca2373d8b73b143d4c8734345c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* vim: set expandtab tabstop=4 shiftwidth=4 : */

import java.util.List;
import java.util.ArrayList;

public class Brute
{

    public static void main(String[] args)
    {
        class Solution implements Comparable<Solution>
        {
            private Point[] pts = new Point[4];

            public Solution(Point p, Point q, Point r, Point s)
            {
                pts[0] = p;
                pts[1] = q;
                pts[2] = r;
                pts[3] = s;
                Insertion.sort(pts);
            }

            public void draw()
            {
                pts[0].drawTo(pts[3]);
            }

            public void print()
            {
                System.out.println(pts[0]+" -> "+pts[1]+" -> "+pts[2]+" -> "+pts[3]);
            }

            public int compareTo(Solution that)
            {
                int r = pts[0].compareTo(that.pts[0]);
                if (r != 0) return r;
                r = pts[1].compareTo(that.pts[1]);
                if (r != 0) return r;
                r = pts[2].compareTo(that.pts[2]);
                if (r != 0) return r;
                return pts[3].compareTo(that.pts[3]);
            }
        }

        In in = new In(args[0]);
        int n = in.readInt();

        StdDraw.setXscale(0, 32768);
        StdDraw.setYscale(0, 32768);

        Point[] pts = new Point[n];
        for (int i = 0; i < n; i++)
        {
            Point p = new Point(in.readInt(), in.readInt());
            pts[i] = p;
            p.draw();
        }

        List<Solution> res = new ArrayList<Solution>();
        for (int p = 0; p < n; p++)
        {
            for (int q = p+1; q < n; q++)
            {
                double sl = pts[p].slopeTo(pts[q]);
                for (int r = q+1; r < n; r++)
                {
                    if (!(sl == pts[p].slopeTo(pts[r])))
                        continue;
                    for (int s = r+1; s < n; s++)
                    {
                        if (sl == pts[p].slopeTo(pts[s]))
                        {
                            res.add(new Solution(pts[p], pts[q], pts[r], pts[s]));
                        }
                    }
                }
            }
        }

        Solution[] sorted = new Solution[res.size()];
        res.toArray(sorted);
        Insertion.sort(sorted);
        for (Solution sol : sorted)
        {
            sol.draw();
            sol.print();
        }
        StdDraw.show(0);
    }
}