Skip to content

Instantly share code, notes, and snippets.

@vijaysharm
Last active August 29, 2015 14:13
Show Gist options
  • Save vijaysharm/c664b83e77856fb6b182 to your computer and use it in GitHub Desktop.
Save vijaysharm/c664b83e77856fb6b182 to your computer and use it in GitHub Desktop.
Trello job application question

Find an 8 letter string of characters that contains only letters from acdegilmnoprstuw such that the hash(the_string) is 25180466553932 if hash is defined by the following pseudo-code:

Int64 hash (String s) {
  Int64 h = 7   
  String letters = "acdegilmnoprstuw"     
  for(Int32 i = 0; i < s.length; i++) {
      h = (h * 37 + letters.indexOf(s[i]))     
  }
  return h
} 

For example, if we were trying to find the 7 letter string where hash(the_string) was 680131659347, the answer would be "leepadg".)

package com.vijaysharma;
public class Solution {
private static final String letters = "acdegilmnoprstuw";
private static final long target = 25180466553932L;
public static void main(String[] args) {
divide_and_conquer();
}
public static void divide_and_conquer() {
char[] test = {'a','a','a','a','a','a','a','a'};
int it = 1;
do {
String string = new String(test);
long hash = hash(string);
long diff = target - hash;
System.out.println((it++) + ": " + string + " h:" + hash + " d:" + diff);
if (diff == 0) {
System.out.println("success!");
break;
}
for (int index = 7; index >= 0; index--) {
double max = Math.pow(37, index);
if (diff >= max) {
int mod = test.length - 1 - index;
int letter = letters.indexOf(test[mod]) + 1;
test[mod] = letters.charAt(letter);
break;
}
}
} while(true);
}
public static void bruteforce() {
for(int a = 0; a < letters.length(); a++ ) {
for(int b = 0; b < letters.length(); b++ ) {
for(int c = 0; c < letters.length(); c++ ) {
for(int d = 0; d < letters.length(); d++ ) {
for(int e = 0; e < letters.length(); e++ ) {
for(int f = 0; f < letters.length(); f++ ) {
for(int g = 0; g < letters.length(); g++ ) {
for(int h = 0; h < letters.length(); h++ ) {
StringBuilder test = new StringBuilder();
test.append(letters.charAt(a));
test.append(letters.charAt(b));
test.append(letters.charAt(c));
test.append(letters.charAt(d));
test.append(letters.charAt(e));
test.append(letters.charAt(f));
test.append(letters.charAt(g));
test.append(letters.charAt(h));
String string = test.toString();
long hash = hash(string);
if (hash == 25180466553932L) {
System.out.println("Success: " + string);
return;
} else {
System.out.println(string + " h: " + hash);
}
}
}
}
}
}
}
}
}
}
private static long hash(String string) {
long h = 7;
for (int i = 0; i < string.length(); i++ ) {
h = (h * 37 + letters.indexOf(string.charAt(i)));
}
return h;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment