-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clusterer.java
66 lines (45 loc) · 1.74 KB
/
Clusterer.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
import java.awt.geom.Point2D;
import java.util.HashSet;
import java.util.Random;
public class Clusterer {
// TODO: Get the data! google maps api
Cluster[] clusters;
public Clusterer(int k, Point2D.Float[] points){
clusters = new Cluster[k];
}
void setClusters(Point2D.Float[] points){
// <editor-fold desc="pick random centroids">
Random r = new Random();
HashSet<Integer> usedNumbers = new HashSet<Integer>();
for(int i = 0; i < clusters.length; i ++){
int ri = r.nextInt(points.length);
while(usedNumbers.contains(ri)) ri = r.nextInt(points.length);
usedNumbers.add(ri);
clusters[i].centroid = points[ri];
}
//</editor-fold>
while(true){
Cluster closest = null;
boolean centroidsSame = true;
for(Point2D.Float p : points){
for(Cluster c : clusters){
if(closest == null) closest = c;
if(Math.pow(p.distanceSq(c.centroid), 2) < Math.pow(p.distanceSq(closest.centroid), 2)){
closest = c;
}
}
closest.members.add(p);
}
// Recalculates
for (Cluster cluster : clusters) {
Point2D oc = cluster.centroid; // Old Centroid for this clusters
Point2D nc = cluster.computeCentroid(); // New Centroid for this cluster
if(!oc.equals(nc)) centroidsSame = false;
}
for (Cluster c : clusters) {
c.members.clear();
}
if (centroidsSame) break;
}
}
}