Skip to content

Instantly share code, notes, and snippets.

@poetix
Created August 21, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poetix/67538f62acb29836a152 to your computer and use it in GitHub Desktop.
Save poetix/67538f62acb29836a152 to your computer and use it in GitHub Desktop.
public class RotationalHash {
public static int hash(String beads) {
byte[] buf = beads.getBytes();
int hash = hashBytes(buf);
int i = 0;
int j = buf.length - 1;
while (i < j) {
buf[i] ^= buf[j];
buf[j] ^= buf[i];
buf[i] ^= buf[j];
i++;
j--;
}
return hash * hashBytes(buf);
}
public static int hashBytes(byte[] buf) {
int windowHash = IntStream.range(0, buf.length)
.map(i -> buf[i] << i)
.sum();
int hash = 1;
for (int start = 0; start < buf.length; start++) {
windowHash = (windowHash - buf[start]) >> 1;
windowHash += buf[start] << (buf.length - 1);
hash *= windowHash;
}
return hash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment