/* * (c) Copyright 2009 Talis Information Ltd * All rights reserved. * [See endLog of file] */ package hash; import com.hp.hpl.jena.tdb.store.Hash ; import org.openjena.atlas.logging.Log ; /** From Project Voldemort / Apache License / Thanks! * who in turn got it from * * Taken from http://www.isthe.com/chongo/tech/comp/fnv * * hash = basis for each octet_of_data to be hashed hash * = hash * FNV_prime hash * = hash xor octet_of_data return hash * */ public class FnvHashFunction implements HashToInt { private static final long FNV_BASIS = 0x811c9dc5; private static final long FNV_PRIME = (1 << 24) + 0x193; @Override public int reduce(Hash hash) { return hash(hash.getBytes()) ; } public int hash(byte[] key) { long hash = FNV_BASIS; for(int i = 0; i < key.length; i++) { hash ^= 0xFF & key[i]; hash *= FNV_PRIME; } return (int) hash; } public static void main(String[] args) { if(args.length != 2) Log.fatal(FnvHashFunction.class, "USAGE: java FnvHashFunction iterations buckets"); int numIterations = Integer.parseInt(args[0]); int numBuckets = Integer.parseInt(args[1]); int[] buckets = new int[numBuckets]; FnvHashFunction hash = new FnvHashFunction(); for(int i = 0; i < numIterations; i++) { int val = hash.hash(Integer.toString(i).getBytes()); buckets[Math.abs(val) % numBuckets] += 1; } double expected = numIterations / (double) numBuckets; for(int i = 0; i < numBuckets; i++) System.out.println(i + " " + buckets[i] + " " + (buckets[i] / expected)); } } /* * (c) Copyright 2009 Talis Information Ltd * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */