Lists Hash Functions

I'm trying to create a hash function, so I can tell if lists of the same size too contain the same elements.

For example, this is what I want:
f ((2 2 1)) = f ((3 1 2)) = f ((3 2)) = f (1)).

Any ideas how I can solve this problem? I tried to make the sum of the squares of all the elements, but it turned out that there are collisions, for example f ((2 2 5)) = 33 = f ((1 4 4)), which is wrong, since the lists are not the same.

I am looking for a simple approach, if any.

+3
source share
7 answers

, , , . N k k 1..N( , ). , , N = 256, k = 8, N k ~ 4 x 10 ^ 14. .

, N, k, . .

, . , ( ) xor , , , MD5 . , , ( , ).

+1

, :

list.each do |current_element|
  hash = (37 * hash + current_element) % MAX_HASH_VALUE
end
+2

, -, ,

1. If h(x1) == y1, then there is an inverse function h_inverse(y1) == x1

2. Because the inverse function exists, there cannot be a value x2 such that x1 != x2, and h(x2) == y1.

Knuth

Knuth " " 6.4 -. 2 ^ 32 (2654435761), .

hash(i)=i*2654435761 mod 2^32

2654435761 2 ^ 32 , - . , . - , . , .

96-

-, , / .

Java-, " β†’ > " . C, Java 'int' C 'uint32_t', 'long' Java C 'uint64_t'.

- -.

int mix(int a, int b, int c)
{
  a=a-b;  a=a-c;  a=a^(c >>> 13);
  b=b-c;  b=b-a;  b=b^(a << 8); 
  c=c-a;  c=c-b;  c=c^(b >>> 13);
  a=a-b;  a=a-c;  a=a^(c >>> 12);
  b=b-c;  b=b-a;  b=b^(a << 16);
  c=c-a;  c=c-b;  c=c^(b >>> 5);
  a=a-b;  a=a-c;  a=a^(c >>> 3);
  b=b-c;  b=b-a;  b=b^(a << 10);
  c=c-a;  c=c-b;  c=c^(b >>> 15);
  return c;
}

+1

, , , , + 1.

... , 9 ( ), :

f (2 3 9 8) = f (3 8 9 2) = 2389

99, :

f (16 2 76 8) = (0) 2081676

2,2 5, , 5, "" 6, :

f (2 2 5) = 2 * 6 ^ 2 + 2 * 6 + 5 = 89 f (1 4 4) = 1 * 6 ^ 2 + 4 * 6 + 4 = 64

0

- , ( , , , - ) Boost

template <class T>
void hash_combine(size_t& seed, T const& v)
{
  seed ^= hash_value(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}

, , xor ( ).

, , , , , O (N log N), .

, -, , ...

0

-, , .

[...], ,

, . ( " ", ) , , . , , .

- , . , , .

: , , . ( -), -.

:

2 1 3

1 2 3

,

2^1.3^2.5^3

2.9.125 = 2250

2250 , , 1 2 3, - , .

0

( ) , ( Python HashSet Java). , -, . .

0

Source: https://habr.com/ru/post/1746643/


All Articles