package algorithm.tokroom;
import java.util.*;
public class Anagram {
public static void main(String[] args) {
String[] strs = {"eat", "repaid", "paired" ,"tea", "bat"};
String[][] answer = solution(strs);
for (String[] strLine : answer) {
System.out.print("{");
int index = 0;
for (String str : strLine) {
System.out.print(str);
if (++index != strLine.length) {
System.out.print(", ");
}
}
System.out.println("}");
}
}
static String[][] solution(String[] strs) {
int LengthOfRow = 0;
boolean[] isChecked = new boolean[strs.length];
Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
for (int i = 0; i < strs.length; i++) {
if (isChecked[i]) {
continue;
}
List<String> list = new ArrayList<String>();
list.add(strs[i]);
isChecked[i] = true;
char[] arr = strs[i].toCharArray();
Arrays.sort(arr);
for (int j = i + 1; j < strs.length; j++) {
if (isChecked[j]) {
continue;
}
char[] arr2 = strs[j].toCharArray();
Arrays.sort(arr2);
if (Arrays.toString(arr).equals(Arrays.toString(arr2))) {
list.add(strs[j]);
isChecked[j] = true;
}
}
map.put(LengthOfRow, list);
++LengthOfRow;
}
String[][] res = new String[LengthOfRow][];
for (int i = 0; i < LengthOfRow; i++) {
res[i] = new String[map.get(i).size()];
for (int j = 0; j < map.get(i).size(); j++) {
res[i][j] = map.get(i).get(j);
}
}
return res;
}
}