-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSPPoint.c
77 lines (69 loc) · 1.67 KB
/
SPPoint.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
67
68
69
70
71
72
73
74
75
76
77
#include <stdlib.h> // malloc, free
#include <assert.h> // assert
#include "SPPoint.h"
struct sp_point_t {
double* data;
int dim;
int index;
};
SPPoint spPointCreate(double* data, int dim, int index) {
// Function variables
SPPoint point;
double* pointData;
int i; // Generic loop variable
if (index < 0 || dim <= 0 || data == NULL) {
return NULL; // Invalid parameters
}
point = (SPPoint) malloc(sizeof(struct sp_point_t));
if (point == NULL) { // Allocation Fails
return NULL;
}
pointData = (double*) malloc(sizeof(double)*dim);
if (pointData == NULL) { // Allocation Fails
free(point);
return NULL;
}
for (i=0;i<dim;i++) {
pointData[i] = data[i];
}
point->data = pointData;
point->index = index;
point->dim = dim;
return point;
}
SPPoint spPointCopy(SPPoint source) {
SPPoint newPoint;
assert(source != NULL);
newPoint = spPointCreate(source->data, source->dim, source->index); // Create new copy of source
return newPoint;
}
void spPointDestroy(SPPoint point) {
if (point != NULL) {
free(point->data);
free(point);
}
}
int spPointGetDimension(SPPoint point) {
assert(point != NULL);
return point->dim;
}
int spPointGetIndex(SPPoint point) {
assert(point != NULL);
return point->index;
}
double spPointGetAxisCoor(SPPoint point, int axis) {
assert(point != NULL && axis < point->dim && axis >= 0);
return point->data[axis];
}
double spPointL2SquaredDistance(SPPoint p, SPPoint q) {
// Function variables
int i; // Generic loop variable
double L2Dist=0,axis;
assert(p != NULL && q != NULL && p->dim == q->dim);
// Calculate squared distance
for (i=0;i<p->dim;i++) {
axis = p->data[i] - q->data[i];
L2Dist += axis*axis;
}
return L2Dist;
}