Created
August 21, 2015 07:28
-
-
Save poetix/67538f62acb29836a152 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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