在平面直角坐标系中,两点可以确定一条直线。如果有多点在一条直线上, 那么这些点中任意两点确定的直线是同一条。
给定平面上 2 × 3 个整点 {(x, y)|0 ≤ x < 2, 0 ≤ y < 3, x ∈ Z, y ∈ Z},即横坐标 是 0 到 1 (包含 0 和 1) 之间的整数、纵坐标是 0 到 2 (包含 0 和 2) 之间的整数 的点。这些点一共确定了 11 条不同的直线。
给定平面上 20 × 21 个整点 {(x, y)|0 ≤ x < 20, 0 ≤ y < 21, x ∈ Z, y ∈ Z},即横 坐标是 0 到 19 (包含 0 和 19) 之间的整数、纵坐标是 0 到 20 (包含 0 和 20) 之 间的整数的点。请问这些点一共确定了多少条不同的直线。
import java.util.*;
public class test3 {
public static void main(String[] args) {
HashMap<Double, Double> hashmap1 = new HashMap<Double, Double>();
for(int x1 = 0;x1 < 20;x1++) {
for(int y1 = 0;y1 < 21;y1++) {
for(int x2 = 0;x2 < 20;x2++) {
for(int y2 = 0;y2 < 21;y2++) {
if(x1-x2 != 0 && y1 != y2) {
double k = (double)(y2-y1)/(x2-x1);
double b = y2-(k*x2);
if(hashmap1.isEmpty()) {
hashmap1.put(k, b);
// System.out.println(hashmap1);
}
else {
Set<Double> keys = hashmap1.keySet();
for(Double key : keys) {
if(Math.abs(key - k) > 1e-4 && Math.abs(hashmap1.get(key) - b) > 1e-4) {
hashmap1.put(k, b);
// System.out.println(key+" "+hashmap1.get(key));
// System.out.println(key-k);
}
}
}
}
}
}
}
}
System.out.println(hashmap1.size()+20+21);
}
}
在迭代的时候如果同时对其进行修改就会抛出java.util.ConcurrentModificationException异常
import java.util.*;
public class Main {
private static final int SPEED = 10;
public static void main(String[] args) {
HashMap<Double, Double> hashmap1 = new HashMap<Double, Double>();
HashMap<Double, Double> hashmap2 = new HashMap<Double, Double>();
for (int x1 = 0; x1 < 20; x1++) {
for (int y1 = 0; y1 < 21; y1++) {
for (int x2 = 0; x2 < 20; x2++) {
for (int y2 = 0; y2 < 21; y2++) {
if (x1 - x2 != 0 && y1 != y2) {
double k = (double) (y2 - y1) / (x2 - x1);
double b = y2 - (k * x2);
if (hashmap1.isEmpty()) {
hashmap1.put(k, b);
// System.out.println(hashmap1);
} else {
hashmap2.putAll(hashmap1);
Set<Double> keys = hashmap2.keySet();
for (Double key : keys) {
if (Math.abs(key - k) > 1e-4 && Math.abs(hashmap1.get(key) - b) > 1e-4) {
hashmap1.put(k, b);
}
}
}
}
}
}
}
System.out.println(hashmap1.size() + 20 + 21);
}
}
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!这还不明显吗,因为你没给考官买礼