diff options
author | flu0r1ne <flu0r1ne@flu0r1ne.net> | 2021-11-28 19:04:35 -0600 |
---|---|---|
committer | flu0r1ne <flu0r1ne@flu0r1ne.net> | 2021-11-28 19:04:35 -0600 |
commit | 7413e6d8a870788817fd1aff80e4a472f03fab9d (patch) | |
tree | 561b19728f09b96055589b3150a88ba46d16768c /kdtest.cpp | |
download | kdtree-wrapper-main.tar.xz kdtree-wrapper-main.zip |
Diffstat (limited to 'kdtest.cpp')
-rw-r--r-- | kdtest.cpp | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/kdtest.cpp b/kdtest.cpp new file mode 100644 index 0000000..147b16c --- /dev/null +++ b/kdtest.cpp @@ -0,0 +1,64 @@ +/* + Test of the KDTree library + https://github.com/jtsiomb/kdtree +*/ + +#include <kdtree.h> +#include <assert.h> +#include <stddef.h> +#include <stdint.h> +#include <stdio.h> +#include <math.h> + +struct xyl_point { + double x; + double y; + uint32_t label; +}; + +int kd_insert_xyl(struct kdtree *tree, struct xyl_point const * pt) { + return kd_insert(tree, (double *) pt, (void *) (&pt->label)); +} + +double l2_norm(struct xyl_point * const x1, struct xyl_point * const x2) { + return sqrt( + (x1->x - x2->x) * (x1->x - x2->x) + + (x1->y - x2->y) * (x1->y - x2->y) + ); +} + +int main() { + struct xyl_point points[5] = { + {0, 0, 0}, + {0, 1, 1}, + {1, 0, 2}, + {1, 1, 3} + }; + + struct kdtree *ptree = kd_create(2); + + for(size_t i = 0; i < sizeof(points); i++) { + assert(0 == kd_insert_xyl(ptree, points + i)); + } + + { + struct xyl_point target = {0.75, 0.80, 0}; + struct xyl_point found; + double dist; + struct kdres * presults = kd_nearest(ptree, (double*) &target); + + while(!kd_res_end(presults)) { + found.label = *(uint32_t*) kd_res_item(presults, (double *) &found); + + dist = l2_norm(&found, &target); + + printf("found [(%.3f, %.3f), %u] a distance of %.3f\n", found.x, found.y, found.label, dist); + + kd_res_next(presults); + } + + kd_res_free( presults ); + } + + kd_free(ptree); +} |