Associative noncommutative hash function

白昼怎懂夜的黑 提交于 2019-12-23 09:32:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!