📄 cluster.cpp
字号:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
typedef float Type;
#define Max 100
int d;
float dist;
int count=0;
typedef struct Node
{
Type *item;
Node* next;
}LNode,*Linklist;
struct Cluster //类的结构
{
int size;
float *center;
Linklist member;
}*cluster;
int ReadData(FILE *fp, Type *data) //从文件中读取数据
{
for(int i=0;i<d+1;i++)
if(feof(fp)) return 0;
else fscanf(fp,"%f",&data[i]);
return 1;
}
void CreateList(Linklist &L)
{
L=(Linklist)malloc(sizeof(LNode));
L->next=NULL;
};
void insertList(Linklist &L,Type *data) //将一值插入列表
{
Linklist p;
int i;
p=(Linklist)malloc(sizeof(LNode));
p->item=(Type *)malloc(sizeof(Type)*(d+1));
for(i=0;i<d+1;i++)
p->item[i]=data[i];
p->next=L->next;
L->next=p;
};
void initcluster(int i)
{
cluster[i].size=0;
CreateList(cluster[i].member);
cluster[i].center=(float *)malloc(sizeof(float)*d);
}
float distance(Type* a,Type* b) //两个值之间的欧几里得距离
{
float dist=0.0;
int i;
for(i=0;i<d;i++)
dist+=(a[i]-b[i])*(a[i]-b[i]);
return (float)sqrt(dist);
}
float findclosedist(Type *temp,int q,int &t)
{
float MinDist, des;
int i=0;
MinDist=65536.0;
for(i=0;i<q;i++)
{
des=distance(temp,cluster[i].center);
if (des<MinDist) {
MinDist=des;
t=i;
}
}
return MinDist;
}
void main()
{
FILE *fp;
Type *temp;
fp=fopen("parameter.txt","r");
fscanf(fp,"%d %f",&d,&dist);
fclose(fp);
temp=(Type *)malloc(sizeof(Type)*(d+1));
int i,j,CID;
cluster=(Cluster *)malloc(sizeof(Cluster) * Max);
fp=fopen("mydataset.txt","r");
ReadData(fp,temp);
initcluster(count);
for(i=0;i<d;i++)
cluster[count].center[i]=temp[i];
insertList(cluster[count].member,temp);
count++;
while(ReadData(fp,temp))
{
if(findclosedist(temp,count,CID)<=dist)
{ for(i=0;i<d;i++)
cluster[CID].center[i]=(cluster[CID].center[i]*cluster[CID].size+temp[i])/(cluster[CID].size+1);
insertList(cluster[CID].member,temp);
cluster[CID].size++;
}
else
{
initcluster(count);
for(i=0;i<d;i++)
cluster[count].center[i]=temp[i];
insertList(cluster[count].member,temp);
cluster[count].size++;
count++;
}
};
fclose(fp);
fp=fopen("cluster.txt","w");
printf("%d\n",count);
Linklist p;
for(i=0;i<count;i++)
{
fprintf(fp,"Center %d:",i+1);
for(j=0;j<d;j++)
fprintf(fp,"%f ",cluster[i].center[j]);
fprintf(fp,"\n");
p=cluster[i].member->next;
while(p)
{
for(j=0;j<d;j++)
fprintf(fp,"%f ",p->item[j]);
fprintf(fp,"%d\n",(int)p->item[d]);
p=p->next;
}
fprintf(fp,"\n");
}
fclose(fp);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -