Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created November 12, 2014 05:40
Show Gist options
  • Save sscovil/6d40dab7135cb8f14ab7 to your computer and use it in GitHub Desktop.
Save sscovil/6d40dab7135cb8f14ab7 to your computer and use it in GitHub Desktop.
An exercise to create a function that, given a string, returns the most commonly-used letter (or letters, in the case of a tie). It should only consider letters and should gracefully handle strings that do not contain letters.
import junit.framework.Assert;
import org.junit.Test;
import java.util.*;
public class MostCommonLetterTests {
public Character[] mostCommonLetter(String string) {
if (string.isEmpty())
throw new IllegalArgumentException("Empty string can not be evaluated for most common letter.");
Map<Character, Integer> counter = new HashMap<>();
for (int i = 0; i < string.length(); i++) {
char character = string.charAt(i);
if (!Character.isLetter(character))
continue;
int count = 1;
if (counter.containsKey(character))
count += counter.get(character);
counter.put(character, count);
}
if (counter.isEmpty())
throw new IllegalArgumentException("No letters found in string.");
String mostCommon = "";
Integer highestCount = 0;
for (Map.Entry<Character, Integer> entry : counter.entrySet()) {
Character character = entry.getKey();
Integer count = entry.getValue();
if (count.equals(highestCount)) {
mostCommon += character.toString();
highestCount = count;
}
else if (count > highestCount) {
mostCommon = character.toString();
highestCount = count;
}
}
Character[] result = new Character[mostCommon.length()];
for (int i = 0; i < result.length; i++) {
result[i] = mostCommon.charAt(i);
}
return result;
}
@Test
public void mostCommonLetterSucceedsA() {
Character[] character = mostCommonLetter("AABC");
Assert.assertTrue(character[0].equals('A'));
Assert.assertEquals(1, character.length);
}
@Test
public void mostCommonLetterSucceedsB() {
Character[] character = mostCommonLetter("ABBC");
Assert.assertTrue(character[0].equals('B'));
Assert.assertEquals(1, character.length);
}
@Test
public void mostCommonLetterSucceedsC() {
Character[] character = mostCommonLetter("ABCC");
Assert.assertTrue(character[0].equals('C'));
Assert.assertEquals(1, character.length);
}
@Test
public void mostCommonLetterSucceedsAB() {
Character[] character = mostCommonLetter("AABB");
Assert.assertTrue(character[0].equals('A'));
Assert.assertTrue(character[1].equals('B'));
Assert.assertEquals(2, character.length);
}
@Test(expected = IllegalArgumentException.class)
public void mostCommonLetterFailsEmptyString() {
mostCommonLetter("");
}
@Test(expected = IllegalArgumentException.class)
public void mostCommonLetterFailsNoLetters() {
mostCommonLetter("!!!");
}
@Test(expected = NullPointerException.class)
public void mostCommonLetterFailsNullValue() {
mostCommonLetter(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment