Skip to content

Commit afafcf2

Browse files
authored
Merge pull request #114 from johnathanchann/feature/hashing
Hashing implementation for the Coordinate class.
2 parents abe180a + 681cbe8 commit afafcf2

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

include/mcpp/coordinate.h

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,15 @@ struct Coordinate {
7474
*/
7575
Coordinate operator-(const Coordinate& obj) const;
7676

77+
/**
78+
* @brief Implements hash algorithm for Coordinate object using non-negative
79+
* mapping and weighted coordinate values.
80+
*
81+
* @param obj The Coordinate object to hash.
82+
* @return Hash of Coordinate object.
83+
*/
84+
std::size_t operator()(const Coordinate& obj) const;
85+
7786
/**
7887
* @brief Outputs the Coordinate object to an ostream.
7988
*

src/coordinate.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,17 @@ Coordinate Coordinate::operator-(const Coordinate& obj) const {
2424
return result;
2525
}
2626

27+
std::size_t Coordinate::operator()(const mcpp::Coordinate& obj) const {
28+
int lower = -3e7, upper = 3e7;
29+
size_t base = upper - lower + 1;
30+
31+
size_t nx = obj.x - lower;
32+
size_t ny = obj.y - lower;
33+
size_t nz = obj.z - lower;
34+
35+
return nx * base * base + ny * base + nz;
36+
}
37+
2738
std::string to_string(const Coordinate& coord) {
2839
using std::to_string;
2940
return "(" + to_string(coord.x) + "," + to_string(coord.y) + "," + to_string(coord.z) + ")";

test/local_tests.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include "../include/mcpp/block.h"
44
#include "../include/mcpp/coordinate.h"
55
#include "doctest.h"
6+
#include <random>
67

78
// NOLINTBEGIN
89

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

26+
SUBCASE("Test hash no collision") {
27+
const int seed = 12345;
28+
std::set<size_t> hashes;
29+
std::mt19937 gen(seed);
30+
std::uniform_int_distribution<int> dis(-3e7, 3e7);
31+
std::uniform_int_distribution<int> dis2(-64, 256);
32+
33+
Coordinate hashing;
34+
for (int i = 0; i < 100; i++) {
35+
Coordinate testCoord(dis(gen), dis2(gen), dis(gen));
36+
size_t hash = hashing(testCoord);
37+
hashes.insert(hash);
38+
}
39+
CHECK_EQ(hashes.size(), 100);
40+
}
41+
2542
SUBCASE("Test double init") {
2643
Coordinate test_coord(1.5, 2.5, 3.5);
2744
Coordinate test_coord_float(1.5F, 2.5F, 3.5F);

0 commit comments

Comments
 (0)