-
Notifications
You must be signed in to change notification settings - Fork 0
/
SPPoint.c
135 lines (101 loc) · 2.18 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
/*
* SPPoint.c
*
* Created on: May 19, 2016
* Author: almog6564
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "SPPoint.h"
#define EPS 0.0000001
struct sp_point_t {
double* data;
int index;
int dim;
};
int spPointCompare(SPPoint a, SPPoint b) {
/*checks if has the same dimension*/
int dim;
if (a->dim != b->dim)
return 1;
else
dim = a->dim;
int i;
int cmp = 0;
for (i = 0; i < dim; i++) {
cmp += (a->data[i] - b->data[i]);
}
if (abs(cmp) > EPS)
return 1;
return a->index - b->index;
}
SPPoint spPointCreate(double* data, int dim, int index) {
if (!data || dim <= 0 || index < 0) {
return NULL;
}
struct sp_point_t * p = (struct sp_point_t*) malloc(
sizeof(struct sp_point_t));
int i;
if (p == NULL) {
return NULL;
}
p->data = (double*) malloc(dim * sizeof(double));
if (p->data == NULL) {
free(p);
return NULL;
}
p->dim = dim;
p->index = index;
for (i = 0; i < dim; i++) {
p->data[i] = data[i];
}
return p;
}
SPPoint spPointCopy(SPPoint source) {
assert(source != NULL);
return spPointCreate(source->data, source->dim, source->index);
}
void spPointDestroy(SPPoint point) {
if (point != NULL) {
free(point->data);
free(point);
}
}
void spPointArrayDestroy(SPPoint* points, int size) {
if (!points || size < 0)
return;
for(int i=0;i<size;i++){
free(points[i]->data);
free(points[i]);
}
free(points);
}
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(axis >= 0);
assert(point!=NULL);
assert(axis < point->dim);
return point->data[axis];
}
double spPointL2SquaredDistance(SPPoint p, SPPoint q) {
assert(p!=NULL);
assert(q!=NULL);
assert(p->dim == q->dim);
register double res = 0, localdist = 0;
register int j, dim = p->dim;
//O(dim)
for (j = 0; j < dim; j++) {
localdist = (p->data[j] - q->data[j]);
localdist *= localdist;
res += localdist;
}
return res;
}