I've a set of inputs strings of the following type,
String[] arr = {"pear", "amleth", "dormitory", "tinsel", "dirty room", "hamlet", "listen", "silent"};
I need to write a program that checks which of these strings are anagrams and print them out in a comma separated list, lexicographically sorted. Thus expected output is
amleth, hamlet
dirty room, dormitory
.......
This is my code
public class Main {
static void checkPrintAnagrams(String[] str){
List<List<String>> out = new ArrayList<>();
int[] check = new int[str.length];
for(int i = 0; i < str.length; i++){
List<String> list = new ArrayList<>();
for(int j= 1; j < str.length; j++){
if(check[j] != 1 && check[i] != 1){
if(isAnagram(str[i], str[j])){
list.add(str[i]);
list.add(str[j]);
check[j] = 1;
check[i] = 1;
}
}
}
out.add(list);
}
Collections.sort(out, new Comparator<List<String>> () {
@Override
public int compare(List<String> a, List<String> b) {
return a.get(1).compareTo(b.get(1));
}
});
for(Iterator itr = out.iterator(); itr.hasNext();){
List<String> l = (List<String>) itr.next();
for(Iterator it = l.iterator(); it.hasNext();){
System.out.print(it.next() + ",");
}
System.out.println();
}
}
static boolean isAnagram(String firstWord, String secondWord) {
char[] word1 = firstWord.replaceAll("[\\s]", "").toCharArray();
char[] word2 = secondWord.replaceAll("[\\s]", "").toCharArray();
Arrays.sort(word1);
Arrays.sort(word2);
return Arrays.equals(word1, word2);
}
public static void main(String[] args) {
// write your code here
String[] arr = {"pear", "amleth", "dormitory", "tinsel", "dirty room", "hamlet", "listen", "silent"};
checkPrintAnagrams(arr);
}
}
The sorting of a List of List part in this code is what I've picked up from the net without understanding completely and like anything not completely understood ends up with an out of bound exception
.
This is my error message.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at io.soumasish.Main$1.compare(Main.java:31)
at io.soumasish.Main$1.compare(Main.java:28)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355)
at java.util.TimSort.sort(TimSort.java:220)
at java.util.Arrays.sort(Arrays.java:1512)
at java.util.ArrayList.sort(ArrayList.java:1454)
at java.util.Collections.sort(Collections.java:175)
at io.soumasish.Main.checkPrintAnagrams(Main.java:28)
at io.soumasish.Main.main(Main.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Would appreciate help in understanding the Collections sort
part and how to implement it correctly in this context.