/*********************************************************************
* Author: Isai Damier
* Title: Count all Characters
* Project: geekviewpoint
* Package: algorithms
*
* Statement:
* Given a text, assume ASCII, count the frequency of each character.
*
* Time Complexity: O(n)
*
* Technical Details:
*
* We could easily solve this problem using a HashMap with character
* keys and integer values.
*
* Map<Character,Integer> map = new HashMap<Character,Integer>();
* Integer freq;
* for(char c : text.toCharArray()){
* freq = map.get(a);
* map.put(a, null == freq? 1 : freq + 1);
* }
* return map;
*
* But that's kind of a heavy solution to such a special problem.
* The set of characters in a human alphabet is very small, e.g. 255
* in extended ASCII. Therefore, it makes more sense to simply use
* an array with 255 elements where the indices represent characters
* and the values represent frequencies. The caller could then cast
* the indices to char.
********************************************************************/
public int[] countAllChars(String text) {
final int ALL_CHARS = 255;
int[] freqency = new int[ALL_CHARS];
for (char c : text.toCharArray()) {
freqency[(int) c]++;
}
return freqency;
}
package algorithms;
import org.junit.Test;
import static org.junit.Assert.*;
public class StringsTest {
/**
* Test of countAllChars method, of class Strings.
* Text from King Lear: Albany's coda after the deaths
*/
@Test
public void testCountAllChars() {
System.out.println("countAllChars");
String text = "The weight of this sad time we must obey, "
+ "Speak what we feel, not what we ought to say. "
+ "The oldest have borne most. We that are young "
+ "Shall never see so much, nor live so long";
Strings instance = new Strings();
int[][] expResult = {
{32, 36}, {44, 3}, {46, 2}, {83, 2}, {84, 2}, {87, 1}, {97, 9},
{98, 2}, {99, 1}, {100, 2}, {101, 21}, {102, 2}, {103, 4}, {104, 11},
{105, 4}, {107, 1}, {108, 6}, {109, 4}, {110, 6}, {111, 13}, {112, 1},
{114, 4}, {115, 9}, {116, 13}, {117, 4}, {118, 3}, {119, 6}, {121, 3}};
int[] result = instance.countAllChars(text);
int ndx = 0;
for (int i = 0; i < result.length && ndx < expResult.length; i++) {
if (i == expResult[ndx][0]) {
if (result[i] != expResult[ndx++][1]) {
fail("miscount");
}
}
}
}
}