Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <float.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <tgmath.h>
- #include <time.h>
- #define CLUSTER 3
- #define ELEMS 1000
- typedef struct {
- complex double z;
- int cluster;
- } elem;
- typedef struct {
- complex double V[2][CLUSTER];
- int flip;
- } center;
- #define center_at(c, i) (c)->V[(c)->flip][(i)]
- static void center_init(center *c) {
- c->flip = 0;
- for (int i = 0; i < CLUSTER; ++i) { c->V[0][i] = c->V[1][i] = 0.; }
- }
- static void center_update(center *c, elem *elems, int n) {
- c->flip = 1 - c->flip;
- complex double s[CLUSTER] = {0};
- int es[CLUSTER] = {0};
- for (int i = 0; i < n; ++i) {
- s[elems[i].cluster] += elems[i].z, ++es[elems[i].cluster];
- }
- for (int i = 0; i < CLUSTER; ++i) { center_at(c, i) = s[i] / es[i]; }
- }
- static int center_reassign(center *c, elem *elems, int n) {
- int change = 0;
- for (int i = 0; i < n; ++i) {
- double d[CLUSTER];
- for (int j = 0; j < CLUSTER; ++j) {
- d[j] = fabs(elems[i].z - center_at(c, j));
- }
- double min = DBL_MAX;
- int next_cluster;
- for (int j = 0; j < CLUSTER; ++j) {
- if (d[j] < min) { min = d[j], next_cluster = j; }
- }
- if (next_cluster != elems[i].cluster) {
- elems[i].cluster = next_cluster, ++change;
- }
- }
- return change;
- }
- static int build_elems(FILE *in, elem *elems, int n) {
- double x, y;
- int used = 0;
- srand(time(NULL));
- while (fscanf(in, "%lf,%lf", &x, &y) == 2) {
- if (n <= used) { exit(1); }
- elems[used].z = CMPLX(x, y), elems[used].cluster = rand() % 3, ++used;
- }
- return used;
- }
- static void output_elems(FILE *out, elem *elems, int n) {
- for (int i = 0; i < n; ++i) {
- fprintf(out, "%f,%f,%d\n", creal(elems[i].z), cimag(elems[i].z),
- elems[i].cluster);
- }
- }
- int main(void) {
- FILE *in = fopen("nocluster.csv", "r");
- elem elems[ELEMS];
- int n = build_elems(in, elems, ELEMS);
- fclose(in);
- center c;
- for (center_init(&c), center_update(&c, elems, n);
- center_reassign(&c, elems, n) > 0; center_update(&c, elems, n)) {
- ;
- }
- FILE *out = fopen("out.csv", "w");
- output_elems(out, elems, n), fclose(out);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement