Skip to content

Instantly share code, notes, and snippets.

@ianbishop
Last active December 12, 2015 02:28
Show Gist options
  • Select an option

  • Save ianbishop/4698738 to your computer and use it in GitHub Desktop.

Select an option

Save ianbishop/4698738 to your computer and use it in GitHub Desktop.
Buckets!!
import java.util.*;
public class BucketTest {
static Random gen = new Random(System.currentTimeMillis());
static int MAX_LENGTH = 64;
public static void main(String[] args) {
int[] buckets = new int[Integer.parseInt(args[0])];
List<String> keys = new ArrayList<String>();
for(int i=0; i < 100000; i++) {
keys.add(randomString());
}
for(String key : keys) {
int hash = key.hashCode();
int index = Math.abs(hash % buckets.length);
buckets[index] = buckets[index] + 1;
}
long sum = 0;
for(int i=0; i < buckets.length; i++) {
sum += buckets[i];
System.out.println("Bucket " + i + ": " + buckets[i]);
}
double mean = (double)sum / (double)buckets.length;
System.out.println("Mean: " + mean);
double variance = 0;
for(int i=0; i < buckets.length; i++) {
variance += Math.pow((double)buckets[i] - mean, 2.0);
}
double std = Math.sqrt(variance / (double)buckets.length);
System.out.println("Standard Deviation: " + std);
}
public static String randomString() {
StringBuilder sb = new StringBuilder();
int len = gen.nextInt(MAX_LENGTH);
char tmp;
for(int i=0; i < len; i++) {
tmp = (char)(gen.nextInt(96) + 32);
sb.append(tmp);
}
return sb.toString();
}
}
@ianbishop

Copy link
Copy Markdown
Author

Update re: http://stackoverflow.com/questions/14665496/variable-range-string-hashing-function-for-odd-prime-buckets/14666226#14666226

Gets pretty good results for small odd n:

Bucket 0: 21225
Bucket 1: 19567
Bucket 2: 19830
Bucket 3: 19797
Bucket 4: 19581
Mean: 20000.0
Standard Deviation: 621.8977407902363

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment