问题
Is there a hash function with following properties?
- is associative
- is not commutative
- easily implementable on 32 bit integers:
int32 hash(int32, int32)
If I am correct, such function allows achieving following goals
- calculate hash of concatenated string from hashes of substrings
- calculate hash concurrently
- calculate hash of list implemented on binary tree - including order, but excluding how tree is balanced
The best I found so far is multiplication of 4x4 matrix of bits, but thats awkward to implement and reduces space to 16bits.
I am grateful for any help.
回答1:
This is what I came up with (written in Java). Basic idea is to split 32bit-int into 2 numbers. Older bits sums including multiplication effect. Younger bits tracks that multiplication effect. It works. It has good distribution - also against common arguments like (0, 1), (1, 0).
public class AssociativelyMergedIntegers {
/** biggest unsigned 16-bit prime */
private static final int PRIME = 65521;
/** associative, not commutative hash function */
public static int merged(int first, int second) {
int firstFactor = remainderOf(first & 0x0000FFFF);
int secondFactor = remainderOf(second & 0x0000FFFF);
int firstSum = remainderOf(first >>> 16 & 0x0000FFFF);
int secondSum = remainderOf(second >>> 16 & 0x0000FFFF);
int resultSum = remainderOf(firstSum + (long) firstFactor * secondSum);
int resultFactor = remainderOf((long) firstFactor * secondFactor);
return resultSum << 16 ^ resultFactor;
}
private static int remainderOf(long number) {
int rest = (int) (number % PRIME);
return rest == 0
? PRIME - 2
: rest;
}
}
来源:https://stackoverflow.com/questions/5491130/associative-noncommutative-hash-function