Reputation: 19
I would like to sort an array based on their group of anagrams.
For Example:
[anew, sale, wane, ales, ascent, seal, wean, leas, secant]
Should output:
[anew, wane, wean, ales, leas, sale, seal, ascent, secant]
Or it could output anagrams on any order as long as they are grouped together.
So I tried doing this:
Arrays.sort(array, (s1, s2) -> {
if (s1.length < s2.length)
return -1;
else if (s1.length > s2.length)
return 1;
else
return s1.compareTo(s2);
});
But I got this:
[secant, leas, wean, seal, ascent, ales, wane, sale, anew]
I know the issue is in the comparator but I can't figure out what is going wrong.
Upvotes: 1
Views: 645
Reputation: 1415
package sandbox;
import java.util.Arrays;
import java.util.List;
public class AnagramSort {
private static final String[] DATA = { "anew", "sale", "wane", "ales", "ascent", "seal", "wean", "leas", "secant" };
public static void main(String[] args) {
List<String> data = Arrays.asList(DATA);
System.out.println(data);
data.sort(AnagramSort::isAnagram);
System.out.println(data);
}
public static int isAnagram(String a, String b) {
char[] s1 = a.toCharArray();
char[] s2 = b.toCharArray();
if (s1.length < s2.length)
return -1;
else if (s1.length > s2.length)
return 1;
Arrays.sort(s1);
Arrays.sort(s2);
return Arrays.compare(s1,s2);
}
}
Results in:
[sale, ales, seal, leas, anew, wane, wean, ascent, secant]
That's probably close to what you need with some tuning done to the isAnagram method (I wrote a crude quick version for this test, and I am not checking is one string is an anagram contained fully inside another larger string).
Upvotes: 0
Reputation: 4705
Your algorithm cannot possibly work, because sorting is achieved by comparing elements locally. To sort by number of anagrams you need to remember what strings are anagrams of one another. This is not a decision, which is possible by comparing two elements without context. You need to identify and collect the anagrams first. Then you can construct the result list.
Upvotes: 2