为了去除重复的直线,一般用斜截式来表示直线,本题采用分数的形式表示斜率和截距
import java.util.*;
class Point{
int x;
int y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
public class Main {
static int gcd(int a, int b) {//最大公约数
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
Point[] points = new Point[420];
int t = 0;
Set<Point> set = new HashSet<>();
Set<String> ans = new HashSet<>();
int x = 19, y = 20;
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++) {
points[t] = new Point(i, j);
set.add(points[t++]);
}
}
List<Point> arr = new ArrayList<>(set);
int len = arr.size();
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
Point a = arr.get(i);
Point b = arr.get(j);
int up = a.y - b.y, down = a.x - b.x;
int c1 = gcd(up, down);
String K = (up / c1) + "/" + (down / c1); //斜率,表示斜率最好这样表示,不用double,表示成分数
if (down == 0) {//不能表示斜率无穷大的时候,需要单独考虑
ans.add("x = " + a.x);
continue;
}
int kx = up * a.x, Y = a.y * down;
int kb = Y - kx;//通分就知道了
int c2 = gcd(kb, down);//别忘了约分
String B = (kb / c2) + "/" + (down / c2); //截距
ans.add(K + " " + B);//K和B都相同才算同一条直线
}
}
System.out.println(ans.size());
}
}