当去重后集合的元素仍大于k时 聚类的过程 迭代 用一个标志 和while()
if (price_all.Count >= k)
{
//cluster the list building element
Random Rd = new Random(); //make a random example
double[] center = new double[k];
double[] oldcenter = new double[k];
int[] ran = new int[k];
int temp_c = price_all.Count;
ran = getNum(k, temp_c);
for (int i = 0; i < center.Length; i++)
{
center[i] = price_all[ran[i]];
}
for (int i = 0; i < oldcenter.Length; i++)
{
oldcenter[i] = 0.0;
}
bool ok = false;
ok = judge(center, oldcenter, ok);
int ireation = 0;
while (!ok)
{
for (int i = 0; i < building_element.Count; i++)
{
//repeat cluster
double temp_price = building_element[i].get_price();
double[] distance = new double[k];
for (int j = 0; j < center.Length; j++)
{
double v = temp_price - center[j];
distance[j] = Math.Sqrt(v * v); // distance
}
//get the min distance
double temp_min = 999999999999999999;
int min_index = 999;
for (int j = 0; j < center.Length; j++)
{
if (distance[j] <= temp_min)
{
temp_min = distance[j];
min_index = j + 1;
}
}
building_element[i].set_type(min_index);
}
for (int n = 0; n < k; n++)
{
oldcenter[n] = center[n];
}
//get averange to be center
double[] total = new double[k];
int[] element_countoftype = new int[k];
for (int n = 0; n < k; n++)
{
for (int i = 0; i < building_element.Count; i++)
{
if (building_element[i].get_type() == n + 1)
{
total[n] += building_element[i].get_price();
element_countoftype[n]++;
}
}
}
int count_no_zero = 0;
for (int n = 0; n < k; n++)
{
if (total[n] != 0.0)
{
count_no_zero++;
}
}
if (count_no_zero == k)
{
for (int n = 0; n < k; n++)
{
center[n] = total[n] / element_countoftype[n];
}
}
else
{
ran = new int[k];
temp_c = price_all.Count;
ran = getNum(k, temp_c);
for (int i = 0; i < center.Length; i++)
{
center[i] = price_all[ran[i]];
}
}
ok = judge(center, oldcenter, ok);
ireation++;
this.Invoke(new setStatusDelegate(setStatus), building_name_all[m], count, ireation);
}
} |