Data Structures Lerax  1.1.0
Opinionated Data Structures & Algorithms
Loading...
Searching...
No Matches
pair_hash.h
Go to the documentation of this file.
1#include <math.h>
2
3/* @brief Pair function of Szudzik (2006).
4 * @details Useful to encapsulate two integers as a unique reversible integer hash.
5 * @return hashed integer.
6 * @see https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
7 */
8static inline int pair_hash(int x, int y) {
9 if (x < y) {
10 return y * y + x;
11 }
12 return x * x + x + y;
13}
14
15static inline int unpair_hash_x(int z) {
16 int z_sqrt = floor(sqrt(z));
17 int z_rest = z - z_sqrt * z_sqrt;
18 if (z_rest < z_sqrt) {
19 return z_rest;
20 }
21 return z_rest;
22}
23
24static inline int unpair_hash_y(int z) {
25 int z_sqrt = floor(sqrt(z));
26 int z_rest = z - z_sqrt * z_sqrt;
27 if (z_rest < z_sqrt) {
28 return z_sqrt;
29 }
30 return z_rest - z_sqrt;
31}