2024-07-23 13:26:16 192 0
有1000个产品,每个产品有长宽高体积属性,从业务上看,长宽高相差不超过指定数的产品,可以认为是相似产品。
我们计算其欧几里得距离:当距离小于阈值时,认为相似。
不过时间复杂度过高。对于少量的产品,还是能够计算的。
import java.util.ArrayList;
import java.util.List;
class Point {
double x, y, z;
Point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
double distance(Point other) {
return Math.sqrt(Math.pow(this.x - other.x, 2) +
Math.pow(this.y - other.y, 2) +
Math.pow(this.z - other.z, 2));
}
}
public class NearestPointsFinder {
public static List<List<Point>> findClosePoints(List<Point> points, double threshold) {
List<List<Point>> closePointsGroups = new ArrayList<>();
for (int i = 0; i < points.size(); i++) {
List<Point> closePoints = new ArrayList<>();
Point currentPoint = points.get(i);
closePoints.add(currentPoint);
for (int j = 0; j < points.size(); j++) {
if (i != j) {
Point otherPoint = points.get(j);
if (currentPoint.distance(otherPoint) < threshold) {
closePoints.add(otherPoint);
}
}
}
// 确保不会将相同的组加入列表
if (!closePoints.isEmpty() && !closePointsGroups.contains(closePoints)) {
closePointsGroups.add(closePoints);
}
}
return closePointsGroups;
}
public static void main(String[] args) {
List<Point> points = new ArrayList<>();
points.add(new Point(1, 2, 3));
points.add(new Point(1.1, 2.1, 3.1));
points.add(new Point(5, 5, 5));
points.add(new Point(5.2, 5.2, 5.2));
double threshold = 0.5; // 距离阈值
List<List<Point>> closePoints = findClosePoints(points, threshold);
// 打印结果
for (List<Point> group : closePoints) {
System.out.print("Close points: ");
for (Point point : group) {
System.out.print("(" + point.x + ", " + point.y + ", " + point.z + ") ");
}
System.out.println();
}
}
}