-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericCluster.java
116 lines (90 loc) · 2.31 KB
/
GenericCluster.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import java.util.*;
/**
* January 2016 Exam problem 2
*/
public class ClusterTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Cluster<Point2D> cluster = new Cluster<>();
int n = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < n; ++i) {
String line = scanner.nextLine();
String[] parts = line.split(" ");
long id = Long.parseLong(parts[0]);
float x = Float.parseFloat(parts[1]);
float y = Float.parseFloat(parts[2]);
cluster.addItem(new Point2D(id, x, y));
}
int id = scanner.nextInt();
int top = scanner.nextInt();
cluster.near(id, top);
scanner.close();
}
}
// your code hereclass Point2D{
class Point2D{
private long id;
private float x;
private float y;
private float distance;
public Point2D(){}
public Point2D(long id, float x, float y) {
this.id = id;
this.x = x;
this.y = y;
}
public double getDistance(Point2D variable){
return Math.sqrt(Math.pow(x-variable.x,2) +(Math.pow(y-variable.y,2)));
}
public void setDistance(float d){
if(d==0.0) distance = Float.MAX_VALUE;
else distance = d;
}
public double getDistance(){
return distance;
}
public String toString(){
return String.format("%d -> %.3f", (int) id , getDistance());
}
public long getId() {
return id;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
}
class Cluster<T extends Point2D> {
List<T> lista ;
public Cluster()
{
lista = new ArrayList<T>();
}
public void addItem(T element)
{
lista.add(element);
}
public void near(long id, int top)
{
Point2D test = new Point2D();
for(int i=0;i<lista.size();i++)
{
if(lista.get(i).getId()==id)
{
test=lista.get(i);
}
}
for(int i=0;i<lista.size();i++)
{
lista.get(i).setDistance((float)lista.get(i).getDistance(test));
}
lista.sort(Comparator.comparing(Point2D::getDistance));
for(int i=0;i<top;i++)
{
System.out.println(i+1+ ". " + lista.get(i).toString());
}
}
}