Home > Mobile >  How to sort a list of strings based on Character Frequency
How to sort a list of strings based on Character Frequency

Time:11-08

I have a list of strings, and i need to sort them based on the Frequency of A's in each word. If the A's are equal then compare the B's, and so on until Z. Assume there are no anagrams in the list ofcourse.

Example: [Banana, Isle, Best, Barb]

Sorted: [Banana, Barb, Best, Isle]

CodePudding user response:

You are sorting on multiple criterias, 26 criterias, that will look like

# for banana, occurence of each char in alphabet
[3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

So build that

from string import ascii_lowercase

def sorter(word: str):
    word_low = word.lower()
    return [word_low.count(c) for c in ascii_lowercase]

values = ["Banana", "Isle", "Best", "Barb"]
values = sorted(values, key=sorter, reverse=True)
print(values)

CodePudding user response:

The words in the initial array can be sorted using comparator for the converted string built from the sorted character array of the given word:

public static String convert(String s) {
    char[] c = s.toLowerCase().toCharArray();
    Arrays.sort(c);
    return new String(c);
}
String[] data = {"Banana", "Isle", "Best", "Barb", "Abracadabra", "aardvark", "Barnabie"};
Arrays.sort(data, Comparator.comparing(MyClass::convert));
System.out.println(Arrays.toString(data));

Output:

[Abracadabra, Banana, aardvark, Barnabie, Barb, Best, Isle]
  • Related