一种基于 xor shift 的序列哈希算法

uint64_t shift(uint64_t x) {
  x ^= x << 13;
  x ^= x >> 17;
  x ^= x << 5;
  return x;
}
uint64_t hsh(vector<int> vec) {
  uint64_t res = 0;
  for (auto x : vec) res = shift(res) + x + 1;
  return res;
}

介绍:没有什么优势的序列哈希,如果能记住 xor-shift 的话可能就好写,但也不非常好

测试代码:

点击查看代码
#!/bin/env python3
mod = 2 ** 64
def shift(x):
    x ^= x << 13
    x %= mod
    x ^= x >> 17
    x %= mod
    x ^= x << 5
    x %= mod
    return x

def hsh(a):
    res = 0
    for x in a:
        res = 1 + x + shift(res)
        res %= mod
    return res

from random import choices, randint
mp = dict()
for i in range(100000):
    a = choices(range(10), k=100)
    r = hsh(a)
    if r in mp and mp[r] != a:
        print(a, mp[r], r)
    mp[r] = a

结果是没碰撞出来

posted @ 2025-04-27 17:11  caijianhong  阅读(82)  评论(0)    收藏  举报