How to write a good hashCode() for permutations?

烂漫一生 提交于 2019-12-22 06:48:55

问题


In my program, I handle a lot of lists of size n that all are permutations of [1,...,n]. My problem is that I put these permutations in HashMaps and HashSets, and I need a good hashCode() that avoids too many collisions.

All the solutions I have thought of lead to either a lot of collisions or an overflow. How can I write a good hashCode for permutations ?


回答1:


Have you tried a 'rotating hash'? You could adjust the barrel rotate amount to see if it makes much difference to the hash distribution.




回答2:


Please see link in karmakaze's answer. It shows a rotating shift in much neater code, and discusses the general details (and issues) with different basic hashes.


An overflow isn't bad. Just modulus it back in :-) Consider just a simple shift with an XOR and feed the "overflow" back into the stream?

Consider, for each element, with value i, where h is a long:

h ^= i;          // XOR in new data
h <<= 11;        // shift with a relatively long cycle
h ^= (h >>> 32); // feed the "overflow" back into the input
h &= 0xFFFF;     // throw out "overflow"

Happy coding.




回答3:


you can take the first n primes and do

int hash = 0;
for(int i = 0; i<n;i++){
    hash +=  perm[i]*prime[i];//really unique will be hash +=Math.pow(prime[i],perm[i]) but will be to computationally heavy
}

the overflow is a pretty good thing as you'll then be sure to have all bits engaged in the hash



来源:https://stackoverflow.com/questions/6051960/how-to-write-a-good-hashcode-for-permutations

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