Hi,

I've been working on this k-means clusterization program. I made mistake somewhere in the code, and program outputs only zeros. I tried to debug it, but I was not able to solve the problem.
I would like to ask for suggestions how to fix my program.

Thanks,

public class kmeans {

    int clusters;
    int[][]points = new int[6][2];
    int[] classification = new int[6];
    int[][] centres = new int[6][6];
    int threshold=2;

public void inputdata(){

    points[0][0]= 0;
    points[0][1]= 0;

    points[1][0]= 1;
    points[1][1]= 1;

    points[2][0]= 2;
    points[2][1]= 2;

    points[3][0]= 5;
    points[3][1]= 3;

    points[4][0]= 6;
    points[4][1]= 6;

}

public void gensentres(){
    for (int i=0; i<6; i++) {
        centres[i][0]=(int)(Math.round(points[0][0]+10*Math.random()));
        centres[i][1]=(int)(Math.round(points[0][1]+10*Math.random()));
    }

}

public boolean distance(int x1, int y1, int x2, int y2) {
    float d=0;
     d = (float) Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
     if (d< threshold) return true; else return false;
}
public void clussifypoints(){
    for (int i=0; i<clusters; i++) {
     for (int j=0; j<6; j++) 
        if (distance(centres[i][0], centres[i][1], points[j][0], 
                points[j][1])) {
            classification[j]=i;
        }
    }
}

public void calcuatecentres(){
    float xavg, yavg;
    int n=0;
    for (int i=0;i<clusters; i++){
        xavg=0; yavg=0;
        for(int j=0;j<6; j++) {
     if (classification[i]==i) {
        xavg = xavg+points[j][0];
        yavg = yavg+points[j][1];
        n++;
     }
        }
        centres[i][0]=(int)xavg/n;
        centres[i][1]=(int)yavg/n;
    }
}

public void addcentre(){
    clusters++;
}

public void mergecentres(){
    clusters--;
}

public void printresults(){
    for (int i=0;i<6; i++)
        System.out.println(classification[i]);
}

public static void main(String[] args) {
 kmeans k = new kmeans();


 k.inputdata();
 k.gensentres();

while (k.clusters!=2) {
k.clussifypoints();
k.calcuatecentres();
 if (k.clusters<2) k.addcentre();
  if (k.clusters>2) k.mergecentres();
}

k.printresults();
}


}

How did you try to debug it? I don't see many printlns statements to show the changes in the variables and the execution flow.
You need to print out everything so you can see what the computer sees. If you understand how the code is supposed to work, when you see what it is doing you should be able to change it so that it does what you want it to do.

Can you post the program's output and explain what is wrong with the output and show what the output should be.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.