Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Forked from sauron/hasher.rb
Last active August 29, 2015 14:00
Show Gist options
  • Save mhewedy/11380342 to your computer and use it in GitHub Desktop.
Save mhewedy/11380342 to your computer and use it in GitHub Desktop.
// direct translation for https://gist.github.com/sauron/9773864
public class Example {
public static void main(String[] args) {
System.out.println(hash("leepadg"));
System.out.println(unhash(680131659347L));
}
static String letters = "acdegilmnoprstuw";
static long hash(String s) {
long h = 7;
for (int i = 0; i < s.length(); i++) {
int var = letters.indexOf(s.charAt(i));
h = (h * 37 + var);
}
return h;
}
static String unhash(long h) {
StringBuffer sb = new StringBuffer();
while (h > 7) {
Object[] obj = getNumberAndChar(h);
h = (long) obj[0];
sb.append((char) obj[1]);
}
return sb.reverse().toString();
}
static Object[] getNumberAndChar(long h) {
for (int i = 0; i < letters.length(); i++) {
if ((h - i) % 37 == 0) {
return new Object[] { h / 37, letters.charAt(i) };
}
}
return new Object[] { 0, '\0' };
}
}
@sauron
Copy link

sauron commented May 20, 2014

Nice! 😉

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