package puzzles;

import java.util.*;

/**
 * Sorts an array of strings so that all the anagrams are next to each other.
 */
public class SortArrayOfStringsWithAnagrams {

  private static final Comparator<String> COMPARATOR = new Comparator<>() {

    private String sortChars(String input) {
      char[] content = input.toCharArray();
      Arrays.sort(content);
      return new String(content);
    }

    public int compare(String s1, String s2) {
      return s1.compareTo(sortChars(s2));
    }
  };

  public String[] sortArrayByAnagrams(String[] unsorted) {
    if (unsorted.length <= 1) {
      return unsorted;
    }

    return Arrays.sort(unsorted, COMPARATOR);
  }
}
