Pairwise independent hash functions in Java

南楼画角 提交于 2019-12-24 09:46:43

问题


I'm looking for a quick and easy way to use a (universal) family of pairwise independent hash functions in my Java projects.

Ideally, I would have some object UniversalFamily (representing the Family) which would return me objects with a method hash() which hashes integers.

Example usage:

// use this object to generate pairwise independent hash functions
UniversalFamily family = new UniversalFamily();

// these objects represent the pairwise independent hash functions
HashF hashF1 = fam.getHashFunction();
HashF hashF2 = fam.getHashFunction();
// ...

/* here the hash functions are being used to hash the integers 1, 2 and 
   1337, the return values (not stored) are the results of the 
   corresponding hash functions. */
hashF1.hash(1);
hashF1.hash(2);
hashF2.hash(1337);
// ...

Before I start tinkering around, is there anything like this already available?


回答1:


Use something like this:

/* Used to generate and encapsulate pairwise independent hash functions.
See see https://people.csail.mit.edu/ronitt/COURSE/S12/handouts/lec5.pdf , claim 5 for more information.
 */
private static class HashF {

    private final int a;
    private final int b;
    private final int p = 1610612741; // prime

    HashF(int a, int b) {
        Random rand = new Random();

        this.a = rand.nextInt(p);
        this.b = rand.nextInt(p);
    }

    // hashes integers
    public int hash(int x) {
        return (a*x + b) % p;
    }

}


来源:https://stackoverflow.com/questions/46917625/pairwise-independent-hash-functions-in-java

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