-
Notifications
You must be signed in to change notification settings - Fork 0
/
point.c
66 lines (56 loc) · 1.58 KB
/
point.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "point.h"
struct Point {
char *id;
double *coordinate;
};
Point *point_construct(char *id, int size) {
Point *p = (Point *) calloc(1, sizeof(Point));
if (p == NULL)
exit(printf("Error: point_construct failed to allocate memory.\n"));
p->coordinate = (double *) calloc(size, sizeof(double));
p->id = strdup(id);
return p;
}
Point *point_read(int size, char *line) {
char *token = strtok(line, ",");
Point *p = point_construct(token, size);
int i = 0;
token = strtok(NULL, ",");
while(token != NULL || i < size) {
// Converte a string para double e armazena no vetor de coordenadas.
p->coordinate[i] = strtod(token, NULL);
token = strtok(NULL, ",");
i++;
}
return p;
}
void point_destroy(Point *p) {
free(p->coordinate);
free(p->id);
free(p);
}
// Debug
void point_print(Point *p, int dimension) {
printf("%s", p->id);
for (int i = 0; i < dimension; i++) {
printf(",%.2f", p->coordinate[i]);
}
printf("\n");
}
double point_euclidean_distance(Point *p1, Point *p2, int dimension) {
double sum = 0;
for (int i = 0; i < dimension; i++)
sum += (p1->coordinate[i] - p2->coordinate[i]) * (p1->coordinate[i] - p2->coordinate[i]);
return sum; // sqrt(sum) não é necessário para comparação.
}
char *point_get_id(Point *p) {
return p->id;
}
int point_compare(const void *a, const void *b) {
Point *p1 = *(Point **)a;
Point *p2 = *(Point **)b;
return strcmp(p1->id, p2->id);
}