Last active
November 1, 2017 19:51
-
-
Save MaxySpark/8542427d7c518cfdf124b4cf883196a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.*; | |
| public class kmean { | |
| public static void main(String[] args) { | |
| int[] dataset = { 2,3,4,10,11,12,20,25,30 }; | |
| ArrayList<Integer> c1 = new ArrayList<Integer>(); | |
| ArrayList<Integer> c2 = new ArrayList<Integer>(); | |
| cluster(dataset,4,12,c1,c2); | |
| System.out.println("C1"); | |
| for(int j=0; j<c1.size();j++) { | |
| System.out.println(c1.get(j)); | |
| } | |
| System.out.println("C2"); | |
| for(int j=0; j<c2.size();j++) { | |
| System.out.println(c2.get(j)); | |
| } | |
| } | |
| public static void cluster(int[]dataset,int m1,int m2,ArrayList<Integer> c1,ArrayList<Integer> c2) { | |
| c1.clear(); | |
| c2.clear(); | |
| int i = 0; | |
| while(i<dataset.length) { | |
| if(dataset[i]<=m1) { | |
| c1.add(dataset[i]); | |
| } else if(dataset[i]>=m2) { | |
| c2.add(dataset[i]); | |
| } else if( Math.abs(m1-dataset[i]) > Math.abs(m2-dataset[i]) ) { | |
| c2.add(dataset[i]); | |
| } else { | |
| c1.add(dataset[i]); | |
| } | |
| i++; | |
| } | |
| if( m1!=mean1(c1) && m2!=mean2(c2) ) { | |
| m1 = mean1(c1); | |
| m2 = mean2(c2); | |
| cluster(dataset, m1, m2,c1,c2); | |
| } | |
| } | |
| public static int mean1(ArrayList<Integer> c1) { | |
| int sum = 0; | |
| for(int j=0; j<c1.size();j++) { | |
| sum = sum + c1.get(j); | |
| } | |
| return sum/c1.size(); | |
| } | |
| public static int mean2(ArrayList<Integer> c2) { | |
| int sum = 0; | |
| for(int j=0; j<c2.size();j++) { | |
| sum = sum + c2.get(j); | |
| } | |
| return sum/c2.size(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment