What is a good hash function for a collection (i.e., multi-set) of integers?

后端 未结 6 1240
不知归路
不知归路 2021-02-05 06:03

I\'m looking for a function that maps a multi-set of integers to an integer, hopefully with some kind of guarantee like pairwise independence.

Ideally, memory usage woul

6条回答
  •  攒了一身酷
    2021-02-05 06:36

    I have once asked a similar question, "Good hash function for permutations?", and got a hash that worked very well for my use case, I have very few collisions in my working code. It might work well for you too. Calculate something like this:

    // initialize this->hash with 1
    unsigned int hash = 1;
    void add(int x) {
      this->hash *= (1779033703 + 2*x);
    }
    

    So whenever you add a number x, update your hash code with the above formula. The order of the values is not important, you will always get the same hash value.

    When you want to merge two sets, just multiply the hash value.

    The only thing I am not sure if it is possible is to remove a value in O(1).

提交回复
热议问题