import java.util.HashSet; // 导入HashSet集合,用于存储不重复的直线对象。
import java.util.Objects; // 导入Objects类,提供了一些静态方法来操作对象,如计算哈希码和比较对象。
public class 直线 {
/**
* 主方法,程序执行的入口。
*/
public static void main(String[] args) {
HashSet<line> lines = new HashSet<>(); // 创建一个HashSet来存储不重复的直线对象。
// 通过嵌套循环遍历所有可能的点对,以计算不同的直线。
for (int x1 = 1; x1 <= 19; x1++) { // 第一层循环:x1的值从1到19。
for (int y1 = 0; y1 <= 20; y1++) { // 第二层循环:y1的值从0到20。
for (int x2 = 0; x2 <= x1 - 1; x2++) { // 第三层循环:x2的值从0到x1-1,确保x2小于x1,避免重复。
for (int y2 = 0; y2 <= 20; y2++) { // 第四层循环:y2的值从0到20。
line l1 = new line(x1, y1, x2, y2); // 对于每个点对,创建一个新的直线对象。
l1.k_d(); // 计算并设置直线的斜率k和截距d。
lines.add(l1); // 将新的直线对象添加到HashSet中,自动去除重复的直线。
}
}
}
}
System.out.println(lines.size() + 20); // 输出去重后的直线数量加上20的结果。
}
}
class line {
public double k; // 直线的斜率。
public double d; // 直线的截距。
public int x1, y1, x2, y2; // 直线通过的两个点的坐标。
// 构造函数,初始化直线对象。
public line(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
// 计算斜率和截距的方法。
public void k_d() {
if (this.x1 != this.x2) { // 如果两点的x坐标不相同,计算斜率和截距。
this.k = (double) (this.y2 - this.y1) / (this.x2 - this.x1);
this.d = (double) (this.x2 * this.y1 - this.x1 * this.y2) / (this.x2 - this.x1);
} else if (this.y1 == this.y2) { // 如果两点的x坐标相同且y坐标也相同,视为水平直线。
this.k = 0;
this.d = this.y1;
} else { // 如果两点的x坐标相同但y坐标不同,视为垂直直线。
this.k = 999999999; // 用一个非常大的数表示斜率为无限大。
this.d = x1; // 垂直直线的“截距”可以用任意一点的x坐标表示。
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // 自反性检查。
if (o == null || getClass() != o.getClass()) return false; // 类型检查。
line line = (line) o; // 类型转换,将Object转换为line对象。
return Double.compare(k, line.k) == 0 && Double.compare(d, line.d) == 0; // 比较两条直线的斜率和截距是否相等。
}
@Override
public int hashCode() {
return Objects.hash(k, d); // 根据斜率和截距计算hashCode值,确保相同的直线有相同的hashCode。
}
@Override
public String toString() {
return "line{" +
"k=" + k +
", d=" + d +
'}'; // 返回直线对象的字符串表示,包含斜率和截距信息。
}
}
0 回复
0 转发
0 喜欢
5 阅读



