Created
June 26, 2011 14:49
-
-
Save gpiancastelli/1047665 to your computer and use it in GitHub Desktop.
Print the letters of an input string in decreasing order of frequency.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Map.Entry; | |
public class Letters { | |
public static void main(String[] args) { | |
String input = args[0].toLowerCase(); | |
Map<Character, Integer> letterFrequency = new HashMap<Character, Integer>(); | |
for (int i = 0; i < input.length(); i++) { | |
char c = input.charAt(i); | |
if (!Character.isLetter(c)) | |
continue; | |
if (letterFrequency.containsKey(c)) { | |
int frequency = letterFrequency.get(c); | |
letterFrequency.put(c, ++frequency); | |
} else | |
letterFrequency.put(c, 1); | |
} | |
List<Entry<Character, Integer>> letters = | |
new ArrayList<Entry<Character, Integer>>(letterFrequency.entrySet()); | |
Collections.sort(letters, new Comparator<Entry<Character, Integer>>() { | |
@Override | |
public int compare(Entry<Character, Integer> o1, | |
Entry<Character, Integer> o2) { | |
Float diff = Math.signum(o2.getValue() - o1.getValue()); | |
return diff.intValue(); | |
} | |
}); | |
for (Entry<Character, Integer> letter : letters) | |
System.out.printf("%s: %2d%n", letter.getKey(), letter.getValue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment