-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathpoints_classification.cpp
More file actions
73 lines (62 loc) · 1.85 KB
/
points_classification.cpp
File metadata and controls
73 lines (62 loc) · 1.85 KB
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
#include <iostream>
#include <cstdlib> // or <stdlib.h> rand, srand
#include <ctime> // or <time.h> time
#include <omp.h>
#include <math.h>
#define K 4
using namespace std;
int num_threads;
long num_points;
long** points; // 2D array points[x][0] -> point location, points[x][1] -> distance from cluster mean
int cluster[K][2] = {
{75, 25}, {25, 25}, {25, 75}, {75, 75}
};
long cluster_count[K];
void populate_points() {
// Dynamically allocate points[num_points][2] 2D array
points = new long*[num_points];
for (long i=0; i<num_points; i++)
points[i] = new long[2];
// Fill random points (0 to 100)
srand(time(NULL));
for (long i=0; i<num_points; i++) {
points[i][0] = rand() % 100;
points[i][1] = rand() % 100;
}
// Initialize cluster_count
for (int i=0; i<K; i++) {
cluster_count[i] = 0;
}
}
double get_distance(int x1, int y1, int x2, int y2) {
int dx = x2-x1, dy = y2-y1;
return (double)sqrt(dx*dx + dy*dy);
}
void classify_points() {
#pragma omp parallel for num_threads(num_threads)
for (long i=0; i<num_points; i++) {
double min_dist = 1000, cur_dist = 1;
int cluster_index = -1;
for (int j=0; j<K; j++) {
cur_dist = get_distance(
points[i][0], points[i][1],
cluster[j][0], cluster[j][1]
);
if (cur_dist < min_dist) {
min_dist = cur_dist;
cluster_index = j;
}
}
cluster_count[cluster_index]++;
}
}
int main(int argc, char* argv[]) {
num_points = atol(argv[1]);
num_threads = atoi(argv[2]);
populate_points();
double t1 = omp_get_wtime();
classify_points();
double t2 = omp_get_wtime();
double t = (t2 - t1) * 1000;
cout << "Time Taken: " << t << "ms" << endl;
}