Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast hash for 2 coordinates where order doesn't matter?

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.

like image 693
Andi Gu Avatar asked Sep 05 '16 05:09

Andi Gu


People also ask

Why is hash faster?

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.

How do I use sha256 in Python?

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.

How do you hash integers?

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.


1 Answers

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 :-)

like image 135
Raymond Hettinger Avatar answered Oct 17 '22 23:10

Raymond Hettinger