Skip to content

Instantly share code, notes, and snippets.

@samirketema
Created October 13, 2015 06:31
Show Gist options
  • Save samirketema/7bf3df514632192f15f3 to your computer and use it in GitHub Desktop.
Save samirketema/7bf3df514632192f15f3 to your computer and use it in GitHub Desktop.
Crypto-equivalence
import java.util.*;
class CE{
public static void main(String[] args){
String[] test = {"car", "mom", "dad", "book", "ant", "bob"};
ArrayList<ArrayList<String>> t = ce(test);
}
//This basically transforms each character in temporary cipher that's based on the unique characters found
//within the string you are currently processing. Based off of that information, we are able to keep track of similar
//formations of 1-to-1 mappings of various strings.
static ArrayList<ArrayList<String>> ce(String[] arr){
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for(String s : arr){
HashMap<Character, Character> cipher = new HashMap<Character, Character>();
//This will map from every unique character found in ascending order.
char lastUnique = 'a';
StringBuilder sb = new StringBuilder();
for(Character c : s.toCharArray()){
if(!cipher.containsKey(c)){
cipher.put(c, lastUnique);
//move the last unique character forward
lastUnique++;
}
sb.append(cipher.get(c));
}
String key = sb.toString();
if(map.containsKey(key)){
ArrayList<String> list = map.get(key);
list.add(s);
map.put(key, list);
}
else{
ArrayList<String> list = new ArrayList<String>();
list.add(s);
map.put(key, list);
}
}
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
//iterate through the map.
for(String key : map.keySet()){
ArrayList<String> list = new ArrayList<String>();
list.addAll(map.get(key));
listOfLists.add(list);
}
System.out.println(listOfLists);
return listOfLists;
}
}
@samirketema
Copy link
Author

For example, "mom" is temporarily stored as "aba". This is put into the HashMap. Later on, we come across "dad", which is also temporarily stored as "aba", we simply update the list within that key in the HashMap.

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