Question

I am working a school project to implement a Huffman code on text. The first part of course requires a frequency analysis on the text. Is there a better way aside from a giant switch and an array of counters to do it?

ie:

int[] counters

for(int i = 0; i <inString.length(); i++)
{
switch(inString[i])
    case 'A':
    counters[0]++;
.
.
. 

I would like to do all alpha-numeric characters and punctuation. I am using c++.

Was it helpful?

Solution

Why not:

int counters[256] = {0};
for(int i = 0; i <inString.length(); i++)
    counters[inString[i]]++;
}


std::cout << "Count occurences of \'a\'" << counters['a'] << std::endl;

OTHER TIPS

You can use an array indexed by character:

int counters[256];
for (int i = 0; i < inString.length(); i++) {
    counters[(unsigned char)inString[i]]++;
}

You will also want to initialise your counters array to zero, of course.

using a map seems completely applicable:

map<char,int> chcount;
for(int i=0; i<inString.length(); i++){
  t=inString[i];
  chcount[i]? chcount[i]++ : chcount[i]=1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top