Last active
August 29, 2015 14:03
-
-
Save matovitch/d2887c387dcf11bcfef4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctime> | |
#include <cstddef> | |
#include <algorithm> | |
#include <iostream> | |
#include "kmeans.hpp" | |
static const std::size_t nPoints = 50000; | |
static const std::size_t nClusters = 100; | |
struct Point | |
{ | |
typedef float field_type; | |
float m_x, m_y, m_z; | |
Point& operator=(const Point& point) | |
{ | |
m_x = point.m_x; | |
m_y = point.m_y; | |
m_z = point.m_z; | |
return *this; | |
} | |
Point& operator+=(const Point& point) | |
{ | |
m_x += point.m_x; | |
m_y += point.m_y; | |
m_z += point.m_z; | |
return *this; | |
} | |
Point& operator/=(float k) | |
{ | |
m_x /= k; | |
m_y /= k; | |
m_z /= k; | |
return *this; | |
} | |
}; | |
struct Distance | |
{ | |
typedef float return_type; | |
typedef Point argument_type; | |
float operator()(const Point& lhs, const Point& rhs) | |
{ | |
return (lhs.m_x - rhs.m_x) * (lhs.m_x - rhs.m_x) + | |
(lhs.m_y - rhs.m_y) * (lhs.m_y - rhs.m_y) + | |
(lhs.m_z - rhs.m_z) * (lhs.m_z - rhs.m_z); | |
} | |
}; | |
struct Hasher | |
{ | |
std::size_t operator()(const Point& point) | |
{ | |
return ((reinterpret_cast<const char&>(point.m_x)) << 0) + | |
((reinterpret_cast<const char&>(point.m_y)) << 8) + | |
((reinterpret_cast<const char&>(point.m_z)) << 16); | |
} | |
}; | |
struct RandomPointGenerator | |
{ | |
RandomPointGenerator() | |
{ | |
srand(time(NULL)); | |
} | |
Point operator()() | |
{ | |
Point p; | |
p.m_x = rand() / static_cast<float>(RAND_MAX); | |
p.m_y = rand() / static_cast<float>(RAND_MAX); | |
p.m_z = rand() / static_cast<float>(RAND_MAX); | |
return p; | |
} | |
}; | |
int main() | |
{ | |
typedef kmeans::Algorithm<Distance, Hasher> KMeansAlgorithm; | |
std::vector<Point> pointSet(nPoints); | |
KMeansAlgorithm kmeansAlgorithm; | |
std::generate(pointSet.begin(), pointSet.end(), RandomPointGenerator()); | |
kmeansAlgorithm(pointSet.begin(), pointSet.end(), nClusters); | |
for (KMeansAlgorithm::clusters_iterator it = kmeansAlgorithm.m_clusters.begin(); | |
it != kmeansAlgorithm.m_clusters.end(); | |
it++) | |
{ | |
std::cout << it->m_x << ", " | |
<< it->m_y << ", " | |
<< it->m_z << std::endl; | |
} | |
std::cout << std::getchar(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment