Is there a formula that is a one way hash for 2 coordinates (a, b) and (c, d) to one integer where a, b, c, and d are positive? Order doesn't matter here, so the formula should give the same results when given (a, b), (c, d)
and (c, d), (a, b)
. The order of the actual numbers in each coordinate point matter ((a, b)
is not the same as (b, a)
). Speed is the key here, the formula should be fast and have O(1) complexity.
Note - what I'm doing right now is sorting the two coordinates using Python's building in sort, and then using them as keys in Python's built-in dictionary (so, built-in hashing). I need a faster way of doing this so that I can hash the two coordinates to an integer myself.
In DBMS, hashing is used to search the location of the data without using index structure. This method is faster to search using the short hashed key instead of the original value.
For example: use sha256() to create a SHA-256 hash object. You can now feed this object with bytes-like objects (normally bytes ) using the update() method. At any point you can ask it for the digest of the concatenation of the data fed to it so far using the digest() or hexdigest() methods.
The most commonly used method for hashing integers is called modular hashing: we choose the array size M to be prime, and, for any positive integer key k, compute the remainder when dividing k by M. This function is very easy to compute (k % M, in Java), and is effective in dispersing the keys evenly between 0 and M-1.
You can use the hash() of a frozenset for this.
>>> hash(frozenset([(10, 20), (11, 22)]))
1735850283064117985
>>> hash(frozenset([(11, 22), (10, 20)]))
1735850283064117985
Frozensets were specifically designed for this kind of use case (i.e. frozensets are intrinsically unordered collections that are immutable and hashable).
Hope this answer takes your right to what you needed :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With