我有一个数组列表的数组列表,它存储点之间的距离。在对 arraylist 排序后,我需要保留距离的原始索引,因为我需要在代码的后期找到 K 最近邻。我实现的类没有输出正确的距离索引,而只是输出了数组列表的索引
我尝试实现一个 2D 可比类,但出现了一些错误。
public staticArrayList<ArrayList<Double>>distance(ArrayList<sample_points> points) {
ArrayList<ArrayList<Double>> distArray = new ArrayList<ArrayList<Double>>(points.size());
double dist = 0;
List<Element> elements = new ArrayList<Element>();
for(int i = 0; i<points.size()-1; i++) {
ArrayList<Double> distances = new ArrayList<Double>();
for(int j=i+1; j<points.size(); j++){
// do your calculations here
dist = Math.sqrt(Math.pow(points.get(i).getX() - points.get(j).getX(), 2)
+ Math.pow(points.get(i).getY() - points.get(j).getY(), 2));
distances.add(dist);// add the distance to the current distances list
}
distArray.add(distances);//
}
System.out.print("Distances: "distArray);
System.out.println();
for(int i = 0; i < distArray.size(); i++) {
for (int j = 0; j < distArray.get(i).size(); j++) {
elements.add(new Element(i, distArray.get(i).get(j)));
}
}
Collections.sort(elements);
for(int i = 0; i < elements.size(); i++) {
System.out.println("Dist "+ elements.get(i).distance + " "
+ "Index " + elements.get(i).index+" ");
}
}
这是我的可比类:
class Element implements Comparable<Element>{
public final int index;
public final double distance;
public Element(int index, double distance){
this.index = index;
this.distance = distance;
}
@Override
public int compareTo(Element e){
return Double.valueOf(this.distance).compareTo(Double.valueOf(e.distance));
}
}
预期成绩:
Distances: [[2.8284271247461903, 5.830951894845301, 7.280109889280518],
[3.1622776601683795, 5.0], [2.23606797749979]]
Dist 2.23606797749979 Index 0
Dist 2.8284271247461903 Index 0
Dist 3.1622776601683795 Index 0
Dist 5.0 Index 1
Dist 5.830951894845301 Index 1
Dist 7.280109889280518 Index 2
慕桂英546537
相关分类