-
Notifications
You must be signed in to change notification settings - Fork 0
/
point-nd.c
132 lines (95 loc) · 2.47 KB
/
point-nd.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
#include<stdio.h>
#include<math.h>
// distance = 1, if you want to print the distance else 0.
void printItems(int low, int high, int dimension, int distance);
struct points {
double coordinate[30];
double distance;
} point[30], temp, desired;
int main() {
double x[30];
int i, n, nearby, dimension, j, index, position;
printf("\nEnter the number of dimensions: ");
scanf("%d", &dimension);
printf("\nEnter the number of points: ");
scanf("%d", &n);
for(i=0; i<n; i++) {
printf("\nPoint - %d\n", i+1);
for(j=0; j<dimension; j++) {
printf("Enter co-ordinate-%d: ", j+1);
scanf("%lf", &point[i].coordinate[j]);
}
}
printf("\n\nThese are the entered co-ordinates\n");
printItems(0, n, dimension, 0);
printf("\nEnter the index of desired point: ");
scanf("%d", &index);
printf("\nRequired number of nearby points: ");
scanf("%d", &nearby);
index--;
for(j=0; j<dimension; j++) {
desired.coordinate[j] = point[index].coordinate[j];
}
printf("\n\nThis is the desired co-ordinate\n");
printf("(");
for(j=0; j<dimension-1; j++) {
printf("%lf, ", desired.coordinate[j]);
}
printf("%lf)\n", desired.coordinate[j]);
//Calculate the distance.
for(i=0; i<n; i++) {
point[i].distance = 0;
for(j=0; j<dimension; j++) {
x[j] = pow(point[i].coordinate[j] - desired.coordinate[j], 2);
}
for(j=0; j<dimension; j++) {
point[i].distance = point[i].distance + x[j];
}
point[i].distance = sqrt(point[i].distance);
}
printf("\n\nThese are the distances\n");
printItems(0, n, dimension, 1);
//Sort.
for(i = 0; i < n; i++)
{
position = i;
for(j = i + 1; j <n ; j++)
{
if(point[position].distance > point[j].distance)
position = j;
}
if(position != i)
{
temp = point[i];
point[i] = point[position];
point[position] = temp;
}
}
printf("\n\nThese are the distances after sorting\n");
printItems(0, n, dimension, 1);
printf("\nNearby Points\n");
printItems(1, nearby + 1, dimension, 1);
printf("\n");
return 0;
}
void printItems(int low, int high, int dimension, int distance) {
int i, j;
if(distance == 0) {
for(i=low; i<high; i++) {
printf("%d. (", i+1);
for(j=0; j<dimension-1; j++) {
printf("%lf, ", point[i].coordinate[j]);
}
printf("%lf)\n", point[i].coordinate[j]);
}
}
else {
for(i=low; i<high; i++) {
printf("%d. (", i+1);
for(j=0; j<dimension-1; j++) {
printf("%lf, ", point[i].coordinate[j]);
}
printf("%lf) - %lf\n", point[i].coordinate[j], point[i].distance);
}
}
}