Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions include/mcpp/coordinate.h
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,15 @@ struct Coordinate {
*/
Coordinate operator-(const Coordinate& obj) const;

/**
* @brief Implements hash algorithm for Coordinate object using non-negative
* mapping and weighted coordinate values.
*
* @param obj The Coordinate object to hash.
* @return Hash of Coordinate object.
*/
std::size_t operator()(const Coordinate& obj) const;

/**
* @brief Outputs the Coordinate object to an ostream.
*
Expand Down
11 changes: 11 additions & 0 deletions src/coordinate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ Coordinate Coordinate::operator-(const Coordinate& obj) const {
return result;
}

std::size_t Coordinate::operator()(const mcpp::Coordinate& obj) const {
int lower = -3e7, upper = 3e7;
size_t base = upper - lower + 1;

size_t nx = obj.x - lower;
size_t ny = obj.y - lower;
size_t nz = obj.z - lower;

return nx * base * base + ny * base + nz;
}

std::string to_string(const Coordinate& coord) {
using std::to_string;
return "(" + to_string(coord.x) + "," + to_string(coord.y) + "," + to_string(coord.z) + ")";
Expand Down
17 changes: 17 additions & 0 deletions test/local_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "../include/mcpp/block.h"
#include "../include/mcpp/coordinate.h"
#include "doctest.h"
#include <random>

// NOLINTBEGIN

Expand All @@ -22,6 +23,22 @@ TEST_CASE("Test Coordinate class") {
CHECK_EQ(test_coord.z, 0);
}

SUBCASE("Test hash no collision") {
const int seed = 12345;
std::set<size_t> hashes;
std::mt19937 gen(seed);
std::uniform_int_distribution<int> dis(-3e7, 3e7);
std::uniform_int_distribution<int> dis2(-64, 256);

Coordinate hashing;
for (int i = 0; i < 100; i++) {
Coordinate testCoord(dis(gen), dis2(gen), dis(gen));
size_t hash = hashing(testCoord);
hashes.insert(hash);
}
CHECK_EQ(hashes.size(), 100);
}

SUBCASE("Test double init") {
Coordinate test_coord(1.5, 2.5, 3.5);
Coordinate test_coord_float(1.5F, 2.5F, 3.5F);
Expand Down