Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could I do frequency analysis on a string without using a switch

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++.

like image 791
Maynza Avatar asked Dec 05 '22 03:12

Maynza


1 Answers

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;
like image 55
Alexander Gessler Avatar answered Dec 29 '22 00:12

Alexander Gessler